返回具有Linq lambda表达式的子实体的嵌套实体

时间:2017-03-11 13:57:01

标签: c# entity-framework linq lambda

我正在尝试通过Web Api通过Linq表达式返回一个具有嵌套实体的实体。到目前为止我已经想出了这个: return db.Tracks.Include(x => x.LapTimes);

返回以下内容:

    {  
   "Id":2,
   "Name":"Nurburgring",
   "Length":20800,
   "Country":"Germany",
   "LapTimes":[  
      {  
         "Id":2,
         "Time":6.48,
         "CarId":2,
         "Car":null,
         "TrackId":2
      },
      {  
         "Id":5,
         "Time":6.52,
         "CarId":3,
         "Car":null,
         "TrackId":2
      },
      {  
         "Id":6,
         "Time":6.55,
         "CarId":4,
         "Car":null,
         "TrackId":2
      },
      {  
         "Id":7,
         "Time":6.57,
         "CarId":5,
         "Car":null,
         "TrackId":2
      }
   ]
}

问题在于我无法通过Linq表达式弄清楚如何在LapTime实体内部基于外键“CarId”包含正确的Car实体。

我的实体

public Car()
{
    Laptimes = new List<Lap>();
}

    public int Id { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public List<Lap> Laptimes { get; set; }


}
public class Lap
{
    public int Id { get; set; }
    public double Time { get; set; }

    public int CarId { get; set; }
    [ForeignKey("CarId")]
    public Car Car { get; set; }
    public int TrackId { get; set; }
    [ForeignKey("TrackId")]
    public Track Track { get; set; }

}
public class Track
{
    public Track()
    {
        LapTimes = new List<Lap>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public int Length { get; set; }
    public string Country { get; set; }
    public List<Lap> LapTimes { get; set; }   

}

0 个答案:

没有答案