开发者

Is it possible to have TPH inheritance with overlapping column usage in the subclasses?

Entities

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
}

Mappings

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");
  }
}

Note: ColleagueMap has no mapping for "Home_Phone"

DbContext

public override void OnModelCreating(DbModelBuilder modelBuilder)
{
  ...
  modelBuilder.Configurations.Add(new PersonMap());
  modelBuilder.Configurations.Add(new FriendMap());
  modelBuilder.Configurations.Add(new FamilyMap());
  ...
}

Entity Framework is telling 开发者_如何学Cme that I cannot map two properties to the same column:

System.Data.MetadataException: Schema specified is not valid. Errors: Each property name in a type must be unique. Property name 'Home_Phone' was already defined.

I can't find any examples of TPH inheritance where multiple subclasses map different properties to the same columns. Is this possible in EF?


Short answer is no. Each property must have its own column. It is not possible to map multiple properties in inheritance hierarchy to the same column.


This is now possible with EF6 see: https://entityframework.codeplex.com/workitem/583

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜