Entity framework 在多个DbContext中使用同一实体(EF Core 2)

Entity framework 在多个DbContext中使用同一实体(EF Core 2),entity-framework,entity-framework-core,ef-core-2.0,Entity Framework,Entity Framework Core,Ef Core 2.0,我在一个项目中有两个DbContext(efcore2),它们共享同一个实体。 我的问题是EFCore为该实体创建了两个表 每个DbContext都有自己的模式。事实上,我想创建一个多域(和多DbContext)应用程序,但一个DbContext中的实体是共享的,其他DbContext引用这些实体 上下文: public class CommonContext : DbContext { protected override void OnModelCreating(ModelBuil

我在一个项目中有两个DbContext(efcore2),它们共享同一个实体。 我的问题是EFCore为该实体创建了两个表

每个DbContext都有自己的模式。事实上,我想创建一个多域(和多DbContext)应用程序,但一个DbContext中的实体是共享的,其他DbContext引用这些实体

上下文:

public class CommonContext : DbContext
{

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("common");
    }

    public DbSet<DomainModel.Common.User> Users { get; set; }
}

public class App1DbContext : DbContext
{

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("app1");
    }

    public DbSet<DomainModel.App1.Book> Books { get; set; }
}
我首先使用迁移创建了公共模式:

add-migration -context CommonContext
update-database -context CommonContext
然后,我创建了app1模式:

add-migration -context app1
update-database -context app1
但EF在这两种模式中都创建了“用户”表!EF不理解这两个单独的DbContext共享同一个实体(用户)。我希望EF只在公共模式(CommonContext)中创建用户表


如何解决此问题?

public User Author{get;set;}这里您使用Author作为用户的导航属性,并将book table添加为App1DbContext的属性,因此显然EF core会为两个单独的模式创建两个单独的用户表。据我所知,使用这种方法无法解决此方案。您的app1架构引用了一个对象用户,因此它当然会创建第二个表。不一样。我认为你不能以代码优先的方式到达那里。谢谢你,我想是的。我有两个单独的DBContext,不能在它们之间共享实体。它们对应的数据库可能位于不同的服务器中!你有没有想出解决这个问题的办法?我目前正在处理同样的问题,不知道如何解决
add-migration -context app1
update-database -context app1