【问题标题】:Reference a parent table for a Navigation Property in EF在 EF 中引用导航属性的父表
【发布时间】:2012-07-17 14:33:15
【问题描述】:

我基本上有三个带有 FK 的表

制作

  • MakeId
  • MakeName

型号

  • 型号标识
  • 型号名称
  • MakeId (FK)

车辆

  • 车辆编号
  • 购买日期
  • 型号 ID (FK)

我想在不修改我的数据库的情况下从 Vehicle 中获取导航属性

我试过了:

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);
    }

}

但是,当我这样做时,我收到了一个异常:

属性表达式“d => d.Model.MakeId”无效。这 表达式应该代表一个属性:C#: 't => t.MyProperty' VB.Net:'函数(t)t.MyProperty'。指定多个时 属性使用匿名类型:C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New From { t.MyProperty1, t.MyProperty2 }'。

如何在我的 Make & Vehicle 表上创建导航属性而不将 Vehicle.ModelId 列添加到我的数据库中?

【问题讨论】:

    标签: c# entity-framework-4 navigation-properties


    【解决方案1】:

    EF 不支持这种类型的建模。您可以创建一个环绕Model.Make 的属性,如下所示。但这可能会导致不必要的延迟加载。

    public class Vehicle
    {
        public int VehicleId {get;set}
        <snip>...</snip>
    
        [NotMapped]
        public virtual Make VehicleMake 
        {
            get { return Model.Make; }
            set { Model.Make = value; }
        }
    }
    

    【讨论】:

    • 没关系,我明白这一点,但我怎样才能让 Make.Vehicles 正确映射?
    • @NathanKoop 也有同样的问题。你不能映射它。解决方法是查询数据库并在需要该属性时手动分配它。
    • 感谢您的努力,我会做一些进一步的工作并在这里发布任何更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多