实体框架代码首先创建“鉴别器”列

我使用 EF CF 的方法与 MySQL 的网站。 由于某种原因,EF 在我的 Post 表中创建了一个名为“鉴别器”的列,并包含 VARCHAR“ Post”。

为什么要创建这个列?我能做些什么来避免它被创建吗?开设这个专栏有什么好处吗?

50593 次浏览

< strong > 表-每个层次结构 继承场景中使用并需要 Discriminator列。举个例子,如果你有一个这样的模型..。

public abstract class BaseEntity
{
public int Id { get; set; }
//...
}


public class Post : BaseEntity
{
//...
}


public class OtherEntity : BaseEntity
{
//...
}

... and make the BaseEntity part of the model, for instance by adding a DbSet<BaseEntity> to your derived context, Entity Framework will map this class hierarchy by default into a single table, but introduce a special column - the Discriminator - to distinguish between the different types (Post or OtherEntity) stored in this table. This column gets populated with the name of the type (again Post or OtherEntity).

通过将 [NotMapped]数据注释添加到从基类继承的模型中,可以停止正在创建的列。这将告诉 EF 不要将您的类添加到未来的迁移中,删除鉴别器列。

public class BaseClass
{
}
[NotMapped]
public class InheritingClass : BaseClass
{
}

For completeness, if you want to use the fluent API to stop the inheriting class from being mapped with entity (and therefore stopping the discriminator column being created) you can do the following:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Ignore<InheritingClass>();
}