How to refer to foreign key without HasForeignKey()
Using EF 4.0 with the 4.1 upgrade for POCO / code-first.
OK so I have a domain model where type Car
has, in a collection, multiple objects of type Part
. So a one:many relation.
HasMany(v => v.Parts)
.WithRequired()
.HasForeignKey(v => v.CarId)
.WillCascadeOnDelete();
The problem with this is that it requires me to add a CarId
property to my Part
type. This is leaking ORM detail into my domain model - which is bad. Marking everything virtual is annoying enough.
Looking at the XML doc comment for the HasForeignKey()
method says this:
Configures the relationship to use foreign key property(s) that are exposed in the object model. If the foreign key property(s) are not exposed in the object model then use the Map method.
That's great and all. But it introduces a catch-22 situation because if I refactor my Part
type by removing the CarId
property that I don't want and update my EF model builder to not bother with mapping that property. Then as you can imagine it means I cannot then call HasKey()
for defining the composite key, ala:
HasKey(v =>开发者_如何学编程; new { v.CarId, v.PartId });
HasKey()
doesn't appear to support defining the keys based upon non-Property lambdas.
What is the solution here?
If you absolutely don't like to have foreign key properties in your model you could remove the convention to detect FK properties to avoid that EF marks properties automatically as FK properties ...
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions
.Remove<NavigationPropertyNameForeignKeyDiscoveryConvention>();
}
... and then simply don't specify the FK property in your mapping:
HasMany(v => v.Parts)
.WithRequired()
.WillCascadeOnDelete();
You still need CarId
in your model because it is part of the primary key, but this way it doesn't act anymore as foreign key property.
Just an idea, I am not sure if it works.
Well, what about adding a new key field to CarParts table like CarPartId, so you would not need the composite key. (Composite Key support is not that great when working with ORMs.)
精彩评论