当项目具有相同 class 的多个导航属性时,Linq Include 不起作用

Linq Include not working when item has multiple navigation properties of the same class

我正在为学校做一个项目,但遇到了一些困难。

一个预订有 3 个导航属性、1 个客户和 2 个机场。 要在其中一个预订视图中获取 CustomerCode,我可以使用 (db.Bookings.Include(b => b.Customer))。 当我尝试对 Origin and/or Destination (db.Bookings.Include(b => b.Origin)) 执行相同操作时,没有任何反应。

我可以通过使用第二个查询查找和设置起点和终点来解决这个问题。 (booking.Origin = db.Airports.Find(id)) 但我想知道为什么 Include 不起作用,以及是否有更优雅的方式在预订时加载机场。

预订class

public int BookingID { get; set; }
public int CustomerID { get; set; }
public int OriginID { get; set; }
public int DestinationID { get; set; }

public string Awb { get; set; }
public string ClientRef { get; set; }
public string Info { get; set; }

// Navigation
public virtual Airport Origin { get; set; }
public virtual Airport Destination { get; set; }
public virtual Customer Customer { get; set; }

客户class

public int CustomerID { get; set; }

public string CustomerCode { get; set; }
public string CompanyName { get; set; }
public string VatNumber { get; set; }

机场class

public int AirportID { get; set; }

public string AirportCode { get; set; }

控制器

public ActionResult Index()
{
    var bookings = db.Bookings.Include(b => b.Origin).Include(b => b.Destination).Include(b => b.Customer);
    return View(bookings.ToList());
}

上下文

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;

public class AppContext : DbContext
{
    // You can add custom code to this file. Changes will not be overwritten.
    // 
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, please use data migrations.
    // For more information refer to the documentation:
    // http://msdn.microsoft.com/en-us/data/jj591621.aspx

    public AppContext() : base("name=AppContext")
    {
    }

    public System.Data.Entity.DbSet<Tester.Models.Country> Countries { get; set; }

    public System.Data.Entity.DbSet<Tester.Models.Airport> Airports { get; set; }

    public System.Data.Entity.DbSet<Tester.Models.Customer> Customers { get; set; }

    public System.Data.Entity.DbSet<Tester.Models.Booking> Bookings { get; set; }
}

来源是 属性。不可能用于包含。也许你不喜欢这样尝试:

     Booking.Include(a=> a.Airport)

根据 Alexander Derck 的建议,使用 [ForeignKey] 属性。

预订class

public int BookingID { get; set; }
public int CustomerID { get; set; }
[ForeignKey("Origin")]
public int OriginID { get; set; }
[ForeignKey("Destination")]
public int DestinationID { get; set; }

public string Awb { get; set; }
public string ClientRef { get; set; }
public string Info { get; set; }

// Navigation
public virtual Airport Origin { get; set; }
public virtual Airport Destination { get; set; }
public virtual Customer Customer { get; set; }