这是我的(简化)问题。 课程:
public class RetailExposure
{
public int RetailExposureId { get; set; }
public int RetailModelId { get; set; }
}
public class PocRetailExposure : RetailExposure
{
[NotMapped]
public string IncidentScore { get; set; }
}
和我的OnModelCreating代码:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<RetailExposure>().ToTable("dbo.RetailExposure");
modelBuilder.Entity<RetailExposure>().Map<PocRetailExposure>(p => p.Requires("RetailModelId").HasValue(1).IsRequired());
}
但是当我添加新的Exposure记录时:
context.RetailExposures.Add(new RetailExposure { RetailModelId = 1 });
context.SaveChanges();
我收到以下错误:
System.Data.MappingException:
(6,10) : error 3032: Problem in mapping fragments starting at line 6:Condition
member 'RetailExposure.RetailModelId' with a condition other than 'IsNull=False'
is mapped. Either remove the condition on RetailExposure.RetailModelId or remove
it from the mapping.
我要做的是拥有一个基类'RetailExposure',其派生类由RetailModelId字段确定。派生类不包含数据库中的属性。我似乎已经想出如何配置EF以使用RetailModelId作为鉴别器,但是在保存更改时我仍然会收到此错误。
我是否需要配置上下文以使其工作?或者我是否尝试做EF目前不支持的事情?
我确实知道我可以告诉EF完全忽略派生类,但这不是我想要的。
答案 0 :(得分:3)
不得将Discriminator映射为实体中的属性 - 它不受支持。 Discriminator只是数据库中的一列,它映射到实际实体的子类型。如果您想将鉴别器作为属性,则无法映射TPH。此外,如果您的父实体不是抽象的,它也必须为鉴别器定义值。
类似的东西:
public class RetailExposure
{
public int RetailExposureId { get; set; }
}
public class PocRetailExposure : RetailExposure
{
[NotMapped]
public string IncidentScore { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<RetailExposure>().ToTable("dbo.RetailExposure");
modelBuilder.Entity<RetailExposure>()
.Map<RetailExposure>(p => p.Requires("RetailModelId").HasValue(0))
.Map<PocRetailExposure>(p => p.Requires("RetailModelId").HasValue(1));
}