如何在两个不同的DbContext中的表之间添加关系 [英] How to add relationship between tables in two different DbContext

查看:35
本文介绍了如何在两个不同的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.

这篇关于如何在两个不同的DbContext中的表之间添加关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆