开发者

Entity Framework Inheritance and Persisted Column

开发者 https://www.devze.com 2023-02-21 23:47 出处:网络
I\'m having some problems in entity framework because of an inheritance. So, I have something like this database:

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:

  1. ProfileTypeId in derived tables is a computed column because of that ProfileTypeId 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 neither Company or Person because EF never sends value of computed columns to the database. So inserts will have violation of foreign key because Profile will always have ProfileTypeId set to null.
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消