实体
public abstract class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string WorkPhone { get; set; }
public string Discriminator { get; set; }
}
public class Friend : Person
{
public string HomePhone { get; set; }
}
public class Family : Person
{
public string CellPhone { get; set; }
}
public class Colleague : Person
{
// No home phone
}
映射
public class PersonMap : EntityTypeConfiguration<Person>
{
public PersonMap()
{
Property(t => t.FirstName).HasColumnName("First_Name");
Property(t => t.LastName).HasColumnName("Last_Name");
Property(t => t.WorkPhone).HasColumnName("Work_Phone");
Map<Friend>(m => m.Requires("Discriminator").HasValue("Friend");
Map<Family>(m => m.Requires("Discriminator").HasValue("Family");
Map<Colleague>(m => m.Requires("Discriminator").HasValue("Colleague");
}
}
public class FriendMap : EntityTypeConfiguration<Friend>
{
public FriendMap()
{
Property(t => t.HomePhone).HasColumnName("Home_Phone");
}
}
public class FamilyMap : EntityTypeConfiguration<Family>
{
public FamilyMap()
{
Property(t => t.CellPhone).HasColumnName("Home_Phone");
}
}
注意:ColleagueMap
没有"Home_Phone"
的映射
的DbContext
public override void OnModelCreating(DbModelBuilder modelBuilder)
{
...
modelBuilder.Configurations.Add(new PersonMap());
modelBuilder.Configurations.Add(new FriendMap());
modelBuilder.Configurations.Add(new FamilyMap());
...
}
实体框架告诉我,我无法将两个属性映射到同一列:
System.Data.MetadataException:指定的架构无效。错误: 类型中的每个属性名称必须是唯一的。物业名称 'Home_Phone'已经定义。
我找不到TPH继承的任何示例,其中多个子类将不同的属性映射到相同的列。这可能在EF吗?
答案 0 :(得分:3)
简短的回答是否定的。每个属性都必须有自己的列。无法将继承层次结构中的多个属性映射到同一列。
答案 1 :(得分:1)