EF 4.1 Code First. Table-per-type inheritance with different primary key name from its base class' primary key name

孤人 提交于 2019-12-01 19:45:29

As I know (and I tried it multiple times) code first doesn't support this => your derived type should use same column names for primary key.

This problem can be described very simply: Current fluent mapping implementation doesn't allow overriding mapping rules from parent entity => parent entity defines names of primary key columns in all derived entities.

IMO the most probable reason is that it was really designed as code first where you don't have existing database and you do not have to bother with database naming - it was up to EF to define names as it needed. Once DbContext API was released people started to use it with existing database massively. But here comes a problem: Initial use cases didn't count with this so some scenarios which are pretty easily done in EDMX are not possible. This is one of them.

alex-cooke

Here is a workaround for this issue:

Create a view for the derived table and map your entity class that view. Rename the key column in your view so that it matches the key column in the base table.

eg:

base table User (UserID, FirstName, LastName)

derived table Manager (ManagerID, DepartmentID)

Entity Framework fails to update Manager as the key column is different!

solution:

create view UserManager
as
select
ManagerID as UserID,
DepartmentID
from Manager

Then map the Manager class to the UserManager view, instead of to the Manager table.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!