I have a legacy database schema which I'd like to model with a table-per-type Entity Framework mapping. However the base table and subclass table use different names for the primary key, and EF doesn't seem to like that.
For example:
[Table("People")]
abstract class Person {
[Key, Column("Id")]
public int Id { get; set; }
// Person properties...
}
[Table("Employees")]
class Employee : Person {
[Key, Column("PersonId")]
public new int Id { get; set; }
// Employee-specific properties...
}
That actually does work, at least for reading: Employee
is mapped to a record from the People
table plus a record from the Employees
table. However, Entity Framework does not populate Employee.Id
(it’s always zero), so I’ve resorted to annotating Employee.Id
as [Obsolete]
to ensure that the rest of my code does not attempt to use it.
I fear that using new
in this way seems like a dreadful hack.
Is there a more idiomatic/correct way of doing it?
Okay… I have a bit of a solution for this… The issue was that the only way to declare different key names for the primary key on the base table and the derived table is to declare the key again in the derived class, and that EF was not setting a value for the key on the derived class, so:
[Table("Employees")]
class Employee : Person {
[Key, Column("PersonId")]
public new int Id {get{return base.Id;}set{base.Id=value;}}
}
Declare the key in the derived class but have it delegate to the key property in the base class. When Entity Framework sets the one, it automatically sets both—and that’s fine because by definition they must be the same.