问题
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:
- Remove all navigation properties between the base and inherited objects.
- Remove the foreign key from the inherited objects, and also remove the property mapping for the foreign key in the inherited objects.
- Remove table mapping in the inherited objects.
- Add database generated identity option to the inherited objects' primary key (if you are using identity on the PKs).
- 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:
- In C# define entity Vehicle (VehicleId, Make, Model)
- In C# define entity Car (SomeOtherField), derived from Vehicle //CarId column will map into VehicleId, see below how.
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