EF 6 share the same entity between different DbContexts?

假如想象 提交于 2019-12-14 04:01:12

问题


I am using ASP.NET MVC 5 with EF 6. I am trying to follow DDD patern and I have IdentityContext and AddressContext.

public class IdentityContext : IdentityDbContext<ApplicationUser>
{
    public IdentityContext()
        : base("DefaultConntection", throwIfV1Schema: false)
    {
    }

    public static IdentityContext Create()
    {
        return new IdentityContext();
    }

}

public class AddressContext: DbContext
{
    public AddressContext(): base("DefaultConntection"){}

    public DbSet<Location> Locations { get; set; }
}

When I am trying to extend(add-migration and update-database) my ApplicationUser which belongs to IdentityContext, I am getting "There is already an object named 'Locations' in the database" error.

public class ApplicationUser : IdentityUser
{
    public virtual Nullable<int> LocationId { get; set; }

    public virtual Location Location { get; set; }
}

How could I share Location Entity between IdentityContext and AddressContext?

Any help would be appreciated.


回答1:


A solution would be to have a single context, that contains all of your DbSets, and then just use that to update your database(and nothing else), and then turn off database initialization for each of the other contexts. You can do this by setting it in the constructor of your business contexts:. Example:

public class IdentityContext : IdentityDbContext<ApplicationUser>
{
        public IdentityContext()
            : base("DefaultConntection", throwIfV1Schema: false)
    {
        Database.SetInitializer<IdentityContext>(null);
    }

    public static IdentityContext Create()
    {
        return new IdentityContext();
    }

}

public class AddressContext: DbContext
{
    public AddressContext(): base("DefaultConntection")
    {
        Database.SetInitializer<AddressContext>(null);
    }

    public DbSet<Location> Locations { get; set; }
}


public class MigrationContext:IdentityDbContext<ApplicationUser>
{
        public MigrationContext()
        : base("DefaultConntection", throwIfV1Schema: false)
        {
        }

    public DbSet<Location> Locations { get; set; }
    //Additional DbSets here...
}

In this example, the migration context is inheriting from IdentityDbContext<ApplicationUser>, so that it'll include all of your Identity stuff. A better way to handle the initialization, might be to defining a BaseContext class, that has it turned off, and then just inheriting from that base context, as described here:http://msdn.microsoft.com/en-us/magazine/jj883952.aspx. See this link for a similar question with more info: Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?



来源:https://stackoverflow.com/questions/24378506/ef-6-share-the-same-entity-between-different-dbcontexts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!