简体   繁体   English

多重上下文 ef-core

[英]Multiples contexts ef-core

I'm working with EF Core and I decided split the DbContexts I'm using.我正在使用 EF Core,我决定拆分我正在使用的 DbContexts。 Everything is right but I notice that when I create the migrations for each context, EF tries to create the tables again even if the other context had created that table previously.一切正常,但我注意到当我为每个上下文创建迁移时,EF 会尝试再次创建表,即使其他上下文之前已创建该表。 I think EF Core must be trying to update the tables instead of trying to create them but I don't know why EF Core would do that.我认为 EF Core 必须尝试更新表而不是尝试创建它们,但我不知道 EF Core 为什么会这样做。

AccountsContext :帐户上下文:

 public class AccountsContext : BaseContext<AccountContext>
 {
        public AccountContext(DbContextOptions<AccountsContext> options): base (options){}
    public DbSet<Account> Accounts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Account>().HasKey(a => a.id);
        modelBuilder.Entity<Account>().Property(a => a.Name).HasField("_name");
        modelBuilder.Entity<Account>().Property(a => a.Role).HasField("_role");
        modelBuilder.Entity<Account>().OwnsOne(a => a.Password);
        modelBuilder.Entity<Account>().OwnsOne(a => a.Email);
    }
}

CampaignContext :活动上下文:

public class CampaignContext: BaseContext<CampaignContext>
{
      public CampaignContext(DbContextOptions<CampaignContext> options): base (options){}

    public DbSet<Campaign> Campaing { get; set; }
    private DbSet<Account> Accounts { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Campaing>().ToTable("Campaings");
        modelBuilder.Entity<Campaing>().HasKey(a => a.Id);
        modelBuilder.Entity<Campaing>().HasOne(c => c.Owner);
        modelBuilder.Entity<Account>().ToTable("Accounts");
  }
}

Here is the scaffold of the migration in the campaign context.这是竞选上下文中迁移的脚手架。 EF Core looks like its trying to create the accounts table even if it already exists in the database. EF Core 看起来像是在尝试创建帐户表,即使它已经存在于数据库中。

在此处输入图片说明 在此处输入图片说明

您应该指定要使用的上下文

dotnet ef Update Database -Context DbContext

Ef 核心中的每个上下文都被视为一个单独的数据库,因此您将该表放在两个数据库中我不知道您为什么要这样做,但是在两个迁移中看到该表是正常的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM