问题
I essentially have three tables with FK's
Make
- MakeId
- MakeName
Model
- ModelId
- ModelName
- MakeId (FK)
Vehicle
- VehicleId
- DatePurchased
- ModelId (FK)
I would like a navigation property from Vehicle to Make without modifying my database
I tried:
public class Make
{
public int MakeId {get;set;}
<snip>...</snip>
public virtual Vehicle Vehicles {get;set;}
}
<snip>Model</snip>
public class Vehicle
{
public int VehicleId {get;set}
<snip>...</snip>
public virtual Make VehicleMake {get;set;}
}
public class VehicleMap : EntityTypeConfiguration<Vehicle>
{
public VehicleMap()
{
this.HasKey(t => t.VehicleId);
<snip>...</snip>
this.HasRequired(t => t.VehicleMake)
.WithMany(t => t.Vehicles)
.HasForeignKey(t => t.Model.MakeId);
}
}
However when I did this I received an exception:
The properties expression 'd => d.Model.MakeId' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New From { t.MyProperty1, t.MyProperty2 }'.
How can I create a navigation property on my Make & Vehicle tables without adding Vehicle.ModelId column to my database?
回答1:
EF does not support that type of modeling. You can create a property that wraps around Model.Make
as follows. But it may lead to unnecessary lazy loading.
public class Vehicle
{
public int VehicleId {get;set}
<snip>...</snip>
[NotMapped]
public virtual Make VehicleMake
{
get { return Model.Make; }
set { Model.Make = value; }
}
}
来源:https://stackoverflow.com/questions/11524819/reference-a-parent-table-for-a-navigation-property-in-ef