Mapping TPT in EF Code First 4.1 w/ Different Primary Keys

北城以北 提交于 2019-12-08 19:43:58

问题


I am trying to map a TPT inheritance hierarchy on a legacy database (I can't change column names). All of the examples have the primary keys of the parent and children tables with the same name. Unfortunately, mine doesn't behave this way.

As a simplified example:

Vehicle
----------------
VehicleId
Make
Model
----------------

Car
----------------
CarId        
SomeOtherField
----------------

CarId and VehicleId are actually the same id and are the values that should be used to associate the tables. Is there any support for creating this as a TPT relationship in Code First?


回答1:


Here is a statement about this issue from the EF team:

Unfortunately this isn't possible at this stage. I realize this isn't a great answer but one option would be to create a view that renames the PK/FK column and then map to that.

It's from February 2011. So it was related to an earlier CTP version of EF Code-First. But I believe that this scenario is still not supported in EF 4.1.

Also a similar question here with not satisfying result regarding EF 4.1 Code-First: How can I use TPT inheritance models when primary keys have different names?




回答2:


I got this to work by doing the following:

  1. Remove all navigation properties between the base and inherited objects.
  2. Remove the foreign key from the inherited objects, and also remove the property mapping for the foreign key in the inherited objects.
  3. Remove table mapping in the inherited objects.
  4. Add database generated identity option to the inherited objects' primary key (if you are using identity on the PKs).
  5. Add a map for the base type to the derived type, and (important bit) in the map explicitly map each property not appearing in the base class/table. In the map, also map the derived type to the derived type's table.

That should pretty much do it. The link is to a sample solution in EF <-> RIA <-> Silverlight, which also shows a workaround for a property with an identical name in the base and derived types (the solution is essentially just to rename the property in either the base type or derived types).

http://dotnetdavis.com/upload/content/source.zip




回答3:


I found answer for this article here: http://entityframework.codeplex.com/workitem/2087. For your case you need:

  1. In C# define entity Vehicle (VehicleId, Make, Model)
  2. In C# define entity Car (SomeOtherField), derived from Vehicle //CarId column will map into VehicleId, see below how.
  3. In 'protected override void OnModelCreating(DbModelBuilder modelBuilder)' do this:

    modelBuilder.Entity() .ToTable("Car") .Property(t => t.VehicleId).HasColumnName("CarId");



来源:https://stackoverflow.com/questions/6681169/mapping-tpt-in-ef-code-first-4-1-w-different-primary-keys

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