How to add relationship between tables in two different DbContext

柔情痞子 提交于 2021-02-08 03:35:14

问题


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?

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


回答1:


Short answer: Entity Framework currently doesn't support creating a query which uses more than one context.

For work around: Refer this.



来源:https://stackoverflow.com/questions/39569223/how-to-add-relationship-between-tables-in-two-different-dbcontext

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