我在数据库中有两个DbContext
,并且想让其中一个仅引用一个表(类):
dotnet ef migrations add Mall20200325 --context ApplicationDbContext
在ApplicationDbContext
中只有一个DbSet:
public DbSet<Models.User> Users { get; set; }
但是它仍然会迁移其他表。
我该怎么做?
答案 0 :(得分:0)
您的问题比您使用的是两个-而不是一个
dotnet ef迁移添加了Mall20200325 -context ApplicationDbContext
答案 1 :(得分:0)
我从here找到了以下解决方案。假设您有AccountDbContext
和ApplicationDbContext
上下文。假设在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]
?