I'm having some problems in entity framework because of an inheritance. So, I have something like this database:
PROFILE
Id int identity [PK]
ProfileTypeId int [FK] [PK]
PROFILETYPE
Id int [PK]
COMPANY
ProfileId int [FK] [PK]
ProfileTypeId AS 1 PERSISTED [FK] [PK]
PERSON
ProfileId int [FK] [PK]
ProfileTypeId AS 2 PERSISTED [FK] [PK]
I want to implement inheritance, an PROFILE can be an COMPANY or PERSON, and it is exclusive, so the FK in COMPANY is ProfileId and ProfileTypeId to PROFIL开发者_Go百科E to make it exclusive.
But when I try to create an company in the entity framework it violates the FK in the PROFILE to the PROFILETYPE. Probably because in the COMPANY the ProfileTypeId is persisted, it is not filling the value in the PROFILE, does anyone knows an workaround to make it work with the entity framework?
Thanks!
There are two very big problems in this database schema:
ProfileTypeId
in derived tables is a computed column because of thatProfileTypeId
in the parent table will be also handled as a computed column. EF doesn't allow computed columns in primary keys. Even it it allows them your scenario will not work. You will not be able to insert neitherCompany
orPerson
because EF never sends value of computed columns to the database. So inserts will have violation of foreign key becauseProfile
will always haveProfileTypeId
set to null.- EF doesn't allow a foreign key to be a computed column.
Conclusion: you can't map this in EF.
You must either get rid of ProfileTypeId and ProfileType because that information is completely redundant for EF or you can try to build some view on top of these tables and map that view as Table Per Hierarchy (TPH) and use stored procedures or instead of
triggers to insert data to your tables.
精彩评论