C# EF 6在不同的DBContext之间共享相同的实体?
我正在使用ASP.NETMVC5和EF6。 我正在尝试遵循DDD模式,我有IdentityContext和AddressContextC# EF 6在不同的DBContext之间共享相同的实体?,c#,asp.net-mvc,entity-framework,domain-driven-design,C#,Asp.net Mvc,Entity Framework,Domain Driven Design,我正在使用ASP.NETMVC5和EF6。 我正在尝试遵循DDD模式,我有IdentityContext和AddressContext public class IdentityContext : IdentityDbContext<ApplicationUser> { public IdentityContext() : base("DefaultConntection", throwIfV1Schema: false) { } p
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:IdentityDbContext
{
公共标识上下文()
:base(“defaultcontection”,throwifvv1schema:false)
{
}
公共静态标识上下文创建()
{
返回新的IdentityContext();
}
}
公共类AddressContext:DbContext
{
public AddressContext():base(“defaultcontection”){}
公共数据库集位置{get;set;}
}
当我尝试扩展(添加迁移和更新数据库)属于IdentityContext的ApplicationUser时,我遇到“数据库中已经有一个名为'Locations'的对象”错误
公共类应用程序用户:IdentityUser
{
公共虚拟可空位置ID{get;set;}
公共虚拟位置{get;set;}
}
如何在IdentityContext和AddressContext之间共享位置实体
任何帮助都将不胜感激。一个解决方案是使用一个包含所有数据库集的上下文,然后仅使用该上下文更新数据库(而不使用其他内容),然后关闭其他每个上下文的数据库初始化。您可以通过在业务上下文的构造函数中设置它来实现这一点:。例如:
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...
}
公共类IdentityContext:IdentityDbContext。有关更多信息,请参见此链接以了解类似问题:
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...
}