引用EF中的导航属性的父表 [英] Reference a parent table for a Navigation Property in EF

查看:155
本文介绍了引用EF中的导航属性的父表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上有三张表与FK的

I essentially have three tables with FK's

Make


  • MakeId

  • MakeName

模型


  • ModelId

  • ModelName

  • MakeId(FK)

车辆


  • VehicleId

  • DatePurchased

  • ModelId(FK)

我想要一个导航属性从车辆到Make而不修改我的数据库

I would like a navigation property from Vehicle to Make without modifying my database

我试过:

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:


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

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 }'.

如何在我的Make&车载表不添加Vehicle.ModelId列到我的数据库?

How can I create a navigation property on my Make & Vehicle tables without adding Vehicle.ModelId column to my database?

推荐答案

EF不支持这种类型的建模。您可以创建一个围绕 Model.Make 的财产,如下所示。但是它可能会导致不必要的懒惰加载。

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

这篇关于引用EF中的导航属性的父表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆