I am using EF CF approach for a website with MySQL. For some reason EF creates a column in my Post table called "Discriminator" and contains the VARCHAR "Post".
Why is this column created? Can I do something to avoid it being created? Are there any advantages of having this column?
The Entity Framework Core Fluent API HasDiscriminator method is used to configure aspects of the discriminator column in a table that represents an inheritance hierarchy. By convention, a discriminator column will be configured to use a string data type will be named "Discriminator".
The discriminator column itself is used to distinguish between different classes when class hierarchies are mapped flat or vertical. The idea behind the flat and vertical mapping is that every class is mapped into a single row in the base class table. The discriminator value is used to define the type of each row.
By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.
IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).
The Discriminator
column is used and required in Table-Per-Hierarchy inheritance scenarios. If you for example have a model like this ...
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
).
You can stop the column being created by adding the [NotMapped]
data annotation to the models that are inheriting from your base class. This will tell EF not to add your class to future migrations, removing the discriminator column.
public class BaseClass { } [NotMapped] public class InheritingClass : BaseClass { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With