EF Core "Invalid column name" Discriminator "" inheritance error
I have the following objects:
public abstract class Freezer
{
public int FreezerId { get; set; }
public string Name { get; set; }
public int FreezerTypeId { get; set; }
public int Capacity { get; set; }
}
public class FoodFreezer : Freezer
{
public List<FoodItem> Foods { get; set; }
}
public class ChemicalFreezer : Freezer
{
public List<ChemicalItem> Chemicals { get; set; }
}
As you can see, derived classes Freezer
do not contain any data that will be stored in the database; they only contain navigation properties for certain types of content.
I have the following configurations:
internal class FreezerConfiguration<T> : DbEntityConfiguration<T> where T : Freezer
{
public override void Configure(EntityTypeBuilder<T> builder)
{
builder.ToTable("Freezers");
builder.HasKey(x => x.FreezerId);
builder.Property(x => x.FreezerId).IsRequired();
builder.Property(x => x.Name).IsRequired();
builder.Property(x => x.FreezerTypeId).IsRequired();
builder.Property(x => x.Capacity).IsRequired();
}
}
internal class FoodFreezerConfiguration : FreezerConfiguration<FoodFreezer>
{
public override void Configure(EntityTypeBuilder<FoodFreezer> builder)
{
builder.HasMany(x => x.FoodItems).WithOne(x => x.Freezer);
}
}
When I make a call to get the list FoodFreezer
out of my context, I get the message "Invalid column name" Discriminator ". After some research it seems that I don't like the fact that FoodFreezer
both ChemicalFreezer
point to one table. What do I need to change? Do I need tables the FoodFreezers and ChemicalFreezers databases only with a column FreezerId
which is FK in the Freezers table?
source to share
@ haim770 led me on the right track. I had to add the following to FreezerConfiguration
:
builder.HasDiscriminator(x => x.FreezerTypeId)
.HasValue<FoodFreezer>(FreezerTypeEnum.Food)
.HasValue<ChemicalFreezer>(FreezerTypeEnum.Chemical);
No additional tables or code is required. If I try to get FoodFreezer
using the ID ChemicalFreezer
it will return null
. Very cool.
source to share