问题描述
我有以下实体:
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; }
}
如您所见,派生的 Freezer
类不包含任何将存储在数据库中的数据.它们仅包含特定内容类型的导航属性.
As you can see the derived Freezer
classes do not contain any data that would be stored in the database; they only contain a navigation property of the specific types of contents.
我有以下配置:
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);
}
}
当我打电话从我的上下文中获取 FoodFreezer
的列表时,我收到无效的列名'Discriminator'"错误.经过一些研究,似乎不喜欢 FoodFreezer
和 ChemicalFreezer
指向单个表的事实.我需要更改什么?我是否需要仅具有 FreezerId
列的FoodFreezers和ChemicalFreezers数据库表,而该列是Freezers表的FK?
When I make a call to get a list of FoodFreezer
s from my context, I get a "Invalid column name 'Discriminator'" error. After doing some research, it seems it doesn't like the fact that FoodFreezer
and ChemicalFreezer
point to a single table. What do I need to change? Do I need a FoodFreezers and ChemicalFreezers database tables with only a FreezerId
column that's a FK to the Freezers table?
推荐答案
@ haim770带我走了正确的路.我必须将以下内容添加到我的 FreezerConfiguration
:
@haim770 led me down the right path. I had to add the following to my FreezerConfiguration
:
builder.HasDiscriminator(x => x.FreezerTypeId)
.HasValue<FoodFreezer>(FreezerTypeEnum.Food)
.HasValue<ChemicalFreezer>(FreezerTypeEnum.Chemical);
不需要其他表或代码.如果我尝试使用 ChemicalFreezer
的ID获取 FoodFreezer
,它将返回 null
.真的很酷.
No additional tables or code needed. If I try to get a FoodFreezer
using the ID of a ChemicalFreezer
, it returns null
. Really cool.
这篇关于继承的EF Core“无效的列名'Discriminator'"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!