Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework code first creates "discriminator" column

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?

like image 272
kasperhj Avatar asked Sep 12 '11 20:09

kasperhj


People also ask

What is discriminator column in Entity Framework?

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".

What is discriminator column in database?

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.

How does Entity Framework handle inheritance?

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.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).


2 Answers

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).

like image 69
Slauma Avatar answered Oct 25 '22 19:10

Slauma


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  { } 
like image 32
PontiusTheBarbarian Avatar answered Oct 25 '22 20:10

PontiusTheBarbarian