3

I've posted my problem on codeplex http://entityframework.codeplex.com/workitem/2087.
There are also some questions posted here but they are not successfully answered.

See

Mapping TPT in EF Code First 4.1 w/ Different Primary Keys

Entity Framework 4 - TPT Inheritance in Features CTP5 (code first): rename foreign key column on inherited table

How can I use TPT inheritance models when primary keys have different names?

Is it now possible to have different column names for the primary keys when using TPT? May be with 6.1.0

Community
  • 1
  • 1
Toni Wenzel
  • 2,081
  • 2
  • 24
  • 39

3 Answers3

0

In TPT you're essentially do not want to declare the key in the subclasses, you'd miss the point otherwise.
If you must have a different Id name, just make proxy properties in the subclasses mapping to the base Id one.

public class BaseEntity
{
  public int Id { get; set; }    
}

public abstract class SubEntity : BaseEntity
{
  public BaseId
  {
    get => Id;
    set => Id = value;
  }
} 

Consider marking the sub fields as NotMapped, which in case you shouldn't include them in your LINQ queries.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
0

With EF 6.4 I was able to use the ColumnAttribute to rename the Primary Key column in the dependent class

[Table("Person")]
public class Person
{
    [Key]
    public virtual int PersonId { get; set; }

    // Person atributes...
}

[Table("Employee")]
public class Employee : Person
{
    [Column("EmployeeId")] // <- Name of the primary Key column in the Database
    public override int PersonId { get; set }

    // Employee Attributes

}
Thomas
  • 2,137
  • 1
  • 17
  • 38
-1

Look at this code snip. Its work correct for me:

public partial class Person
{
    // Any other PK name can thrown an exception
    public int ID { get; set; }
}

public partial class Employee : Person
{
    // Hide base class ID
    private new int ID { get; set }

    // Define derived class ID (that wrapped inherited ID)
    [NotMapped]
    public int EmployeeID
    {
        get { return base.PersonID; }
        set { base.PersonID = value; }
    }
}

Now, we must rename the inherited ID (with fluent API) for database table:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Employee>()
        .Property(e => e.ID)
        .HasColumnName("EmployeeID");
}
Farrokh
  • 31
  • 4