Entity framework code first creates "discriminator" column

Entity Framework

Entity Framework Problem Overview


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?

Entity Framework Solutions


Solution 1 - Entity Framework

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

Solution 2 - Entity Framework

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 
{
}

Solution 3 - Entity Framework

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>();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkasperhjView Question on Stackoverflow
Solution 1 - Entity FrameworkSlaumaView Answer on Stackoverflow
Solution 2 - Entity FrameworkPontiusTheBarbarianView Answer on Stackoverflow
Solution 3 - Entity FrameworkMattView Answer on Stackoverflow