I have to create an entity framework model for a badly designed database. The database uses table per type inheritance but it does so with using a PK->FK relationship, not a PK->PK relationship. E.g.
Person
PersonID (PK)
Name
Employee
EmployeeID (PK)
PersonID (FK)
DateStarted
HourlyEmployee
HourlyEmployeeID (PK)
EmployeeID (FK)
HourlyRate
Obviously this is just badly designed, but I can’t change it. Table per type inheritance in the entity framework essentially wants EmployeeID not to exist and the PK for Employee to be PersonID. Is it possible to create a model for this database, or do I choose another tool? any recommendations?
You will not map this as TPT inheritance because your database is configured in the way that doesn’t allow you cheating EF.
If
Employee.EmployeeIDis auto-generated in the database andEmployee.PersonIDis unique (uniqueness must be enforced in the database) you should be able (not tested) to cheat EF by simply mapping:This class will tell EF that
Employeeinherits key from Person (PersonID) and you will hide the real key from EF – this should work if the real key is auto-generated.The problem is your next level of inheritance which breaks this pattern. To make this work your
HourlyEmployeewill have to referencePersonID– notEmployeeID. EF now doesn’t know aboutEmployeeIDexistence so it even cannot map relation withHourlyEmployee.TPT inheritance in code first has one additional limitation – PK column must have the same name in all tables.