EF 6在不同的DbContexts之间共享相同的实体?

时间:2014-06-24 04:46:06

标签: c# asp.net-mvc entity-framework domain-driven-design

我正在使用带有EF 6的ASP.NET MVC 5。 我正在尝试遵循DDD模式,我有IdentityContext和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; }
}

当我尝试扩展(添加迁移和更新数据库)我的属于IdentityContext的ApplicationUser时,我得到了#34;已经有一个名为&#39; Locations&#39;在数据库&#34;错误。

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

    public virtual Location Location { get; set; }
}

我如何在IdentityContext和AddressContext之间共享位置实体?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

解决方案是拥有一个包含所有DbSet的上下文,然后只使用它来更新数据库(而不是其他任何内容),然后关闭每个其他上下文的数据库初始化。您可以通过在业务上下文的构造函数中设置它来完成此操作:例如:

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...
}

在此示例中,迁移上下文继承自IdentityDbContext<ApplicationUser>,因此它将包含您的所有标识内容。处理初始化的更好方法可能是定义一个关闭它的BaseContext类,然后继承该基本上下文,如下所述:http://msdn.microsoft.com/en-us/magazine/jj883952.aspx。有关更多信息的类似问题,请参阅此链接:Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

相关问题