Inheritance 实体框架4.1中派生类中没有其他数据库字段的TPH
这是我的(简化的)问题。 课程包括:Inheritance 实体框架4.1中派生类中没有其他数据库字段的TPH,inheritance,mapping,entity-framework-4.1,Inheritance,Mapping,Entity Framework 4.1,这是我的(简化的)问题。 课程包括: public class RetailExposure { public int RetailExposureId { get; set; } public int RetailModelId { get; set; } } public class PocRetailExposure : RetailExposure { [NotMapped] public string IncidentScore { get; set
public class RetailExposure
{
public int RetailExposureId { get; set; }
public int RetailModelId { get; set; }
}
public class PocRetailExposure : RetailExposure
{
[NotMapped]
public string IncidentScore { get; set; }
}
以及我的onmodel创建代码:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<RetailExposure>().ToTable("dbo.RetailExposure");
modelBuilder.Entity<RetailExposure>().Map<PocRetailExposure>(p => p.Requires("RetailModelId").HasValue(1).IsRequired());
}
我得到以下错误:
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完全忽略派生类,但这不是我想要的。鉴别器不能映射为实体中的属性-它不受支持。鉴别器只是数据库中的一列,它映射到实际实体的子类型。如果希望将鉴别器作为属性,则无法映射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));
}
公共类零售风险敞口
{
public int RetailExposureId{get;set;}
}
公共类风险敞口:零售风险敞口
{
[未映射]
公共字符串IncidentScore{get;set;}
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable(“dbo.RetailExposure”);
modelBuilder.Entity()
.Map(p=>p.Requires(“RetailModelId”).HasValue(0))
.Map(p=>p.Requires(“RetailModelId”).HasValue(1));
}
Ah。当然,您不能将鉴别器映射到类中的属性——如果您能够做到这一点,就不是很OO了!修复了它并使其成为抽象的。测试通过了。耶!谢谢
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));
}