In my Entity Framework Core application I wanted to use the Table Per Hierarchy pattern. So I configured the EF mapping to use a discriminator column:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyDbContext: DbContext | |
{ | |
protected override void OnModelCreating(ModelBuilder builder) | |
{ | |
builder.Entity<Supplier>(b => | |
{ | |
b.ToTable("Supplier"); | |
b.HasDiscriminator(x=> x.SupplierType); | |
}) | |
} | |
} |
This didn’t had the desired effect. As I ran my application I got the following error message:
The entity type 'ForeignSupplier' is part of a hierarchy, but does not have a discriminator value configured.
Whoops! I forgot to specify how EF Core should recognize the different child types. Let’s fix this in our configuration:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyDbContext: DbContext | |
{ | |
protected override void OnModelCreating(ModelBuilder builder) | |
{ | |
builder.Entity<Supplier>(b => | |
{ | |
b.ToTable("Supplier"); | |
b.HasDiscriminator(x=> x.SupplierType) | |
.HasValue<DomesticSupplier>(SupplierType.Domestic) | |
.HasValue<ForeignSupplier>(SupplierType.Foreign); | |
}) | |
} | |
} |