如何在两个不同的DbContext中的表之间添加关系
我有两个DbContext类和其中的一些实体.我知道拥有多个DbContext不是一个好主意,但是我必须做很多工作来更改我的代码!所以我的问题是在具有不同DbContext的两个实体之间添加关系的最佳方案是什么?
I have two DbContext class and some Entities in them. I know this is not good idea to have more than one DbContext but i have to do a lot of works to change my code! so my question is what is the best scenario for add relationship between two Entities with different DbContext?
例如,具有IdentityDb上下文的用户实体和具有SiteDbContext的注释实体之间的一对多关系:
For example an one to many relationship between User Entity with IdentityDb Context and Comment Entity with SiteDbContext :
public class User : IdentityUser
{
public DateTime JoinDate { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this,DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
public class IdentityDb : IdentityDbContext<ApplicationUser>
{
public IdentityDb() : base("DefaultConnection", throwIfV1Schema: false)
{
}
public static IdentityDb Create()
{
return new IdentityDb();
}
}
public class Comment
{
public int CommentId { get; set; }
[Required]
[StringLength(900)]
public string CommentText { get; set; }
[DataType(DataType.Date)]
public DateTime CommentDate { get; set; }
}
public class SiteDb: DbContext
{
public SiteDb(): base("DefaultConnection")
{
}
public DbSet<Comment> Comments{ get; set; }
}
简短答案:实体框架当前不支持创建使用多个上下文的查询.
Short answer: Entity Framework currently doesn't support creating a query which uses more than one context.
有关变通方法:请参考此.
For work around: Refer this.