9
votes

I am trying to understand the inheritance mappings in EF4.

My database has two tables with the following structure:

PersonCategory Table:

  • CategoryID (int) (identity) (PK)
  • CategoryType (nvarchar(50))

Person Table

  • PersonID (int) (identity) (PK)
  • CategoryID (FK from PersonCategory table)
  • Name (nvarchar(50))
  • Description (nvarchar(max))

PersonCategory table has four entries each representing a category - Student, CourseInstructor, Staff and Advisor.

From reading articles online I thought Table Per Hierarchy will be a suitable model for this scenario. So in EF4, I created four entities(Student, CourseInstructor, Staff and Advisor) each inheriting from Person table. I then mapped each of them to the Person table and added a condition to each (eg. CategoryID = 1 for Student entity and CategoryID = 2 for Staff entity) to differentiate from others. I also removed the CategoryID property from Person table and made it abstract class. But I am getting the following error because I deleted the CategoryId property from Person table.

Error 3015: Problem in mapping fragments starting at lines 101, 108, 114, 120, 126, 133:Foreign key constraint 'FK_Person_PersonCategory' from table Person (CategoryID) to table PersonCategory (CategoryID):: Insufficient mapping: Foreign key must be mapped to some AssociationSet or EntitySets participating in a foreign key association on the conceptual side.

Is Table Per Hierarchy a suitable model for this scenario? If not then how should I approach this scenario in EF4?

3

3 Answers

5
votes

Using discriminator columns in associations is problematic. See:-

http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/24380ee6-4753-46a2-a3ed-b1cb2e2d161c

"The key point is a column that will act as discriminator cannot be mapped to an assocation unless it particpates in not null condition."

0
votes

For Table-per-Hierarchy, a single table contains all the columns for all types. You have two tables, so I'm immediately suspicious.

If going for Table-per-Type, then its not right either. You'd only be able to have two types, base and derived, with the PersonCategory table supplying the data for the derived type's property values. But, this would need to have the PersonID as the foreign key, which it doesn't.

Personally, I think you're needlessly fragmenting your entities into different types. You could map all the columns from both tables to one entity, or if possible, change the database schema to suit your needs better.

I'd suggest working with an empty test database and doing TPT and TPH model-first designs and look at the schema that EF builds for your desired setup.

Luke