Reference a parent table for a Navigation Property in EF

半城伤御伤魂 提交于 2019-12-11 07:55:20

问题


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

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