Combining types table and table inheritance in Entity Framework

211 Views Asked by At

Lets say I have a table+class A, another table+class AType that represents different types of A, and a table+class B that inherits from A.

B is a certain type of A, but it's too complex to fit with the other types of A at the data-level and needs to have it's own table at the schema-level - and ofcourse it's own class.

B is still a type of A, so I want to have a record in AType representing B, and the type filed in A records that are actually Bs to point to that record in AType. I also want to be able to add more tables+classes that inherit from A, and have their PK hard-coded.

Now, if I was using SQL directly, I would have made records for the inheritors of A with negative values as their PK. That way, new ATypes added at the data-level, that have positive PKs, will never conflict with the hard-coded schema-level ones, and as a nice bonus I can easily tell which records in A are of hard types and which are of soft types - without having to look at AType.

I'm new to Entity Framework, so I don't want to apply hacker-style solution before I try the conventional way. So what is the convention to approach this problem in Entity Framework?

1

There are 1 best solutions below

1
On

If you want to follow your strange method you must manually handle key values - you will achieve the same result as in SQL but it will be pretty error prone (especially due to concurrency). It will also not generate nice SQL you expect because EF will not understand your logic hidden inside key values so even if you try to query just A, it will join all derived tables to find which records are really just A - that is the way how EF handles TPT inheritance.