EF Core具有两个DbContext。如何指定表格?

时间:2020-03-25 04:24:34

标签: c# entity-framework .net-core entity-framework-core

我在数据库中有两个DbContext,并且想让其中一个仅引用一个表(类):

dotnet ef migrations add Mall20200325 --context ApplicationDbContext

ApplicationDbContext中只有一个DbSet:

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

但是它仍然会迁移其他表。

我该怎么做?

3 个答案:

答案 0 :(得分:0)

您的问题比您使用的是两个-而不是一个

dotnet ef迁移添加了Mall20200325 -context ApplicationDbContext

答案 1 :(得分:0)

我从here找到了以下解决方案。假设您有AccountDbContextApplicationDbContext上下文。假设在AccountDbContext实体Account中已定义,并且我们想从迁移中排除accounts表,而在User实体中有对它的引用。因此:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // Ignored table `accounts` from other DbContext in the migration

    modelBuilder.Entity<Account>(entity => {
        entity.ToView("accounts");
        // If the `acoounts` table has some columns you must introduce their
        // names like this (if the properties' names are different from columns' names)    
        entity.Property(e => e.Id)
              .HasColumnName("id");
        entity.Property(e => e.FirstName)
              .HasColumnName("first_name");
        entity.Property(e => e.LastName)
              .HasColumnName("last_name");
    });
    
    // Define the table `users`

    modelBuilder.Entity<User>(entity => {
        entity.ToTable("users");

        entity.HasIndex(e => e.Id)
           .HasName("users_account_id_foreign");

        entity.Property(e => e.Id)
           .HasColumnName("id")
           .HasColumnType("bigint(20) unsigned");

       entity.HasOne(d => d.Account)
           .WithOne(p => p.Users)
           .HasForeignKey<User>(d => d.Id)
           .HasConstraintName("users_account_id_foreign");
        
    });

}

答案 2 :(得分:0)

“添加-迁移”过程将比较两个IModel实例,一个实例来自您上下文的OnModelCreating,另一个实例编译到您的程序集中并从IMigrationsAssembly服务加载。

MigrationsAssembly实现应仅考虑具有匹配的DbContextAttribute的模型快照和迁移。

如果您看到了意外的迁移操作,那么在创建两个上下文之前,我不得不怀疑您的项目是什么样的。您是否生成了ModelSnapshot属性不匹配的[DbContext]