How to get only the first element with Include()?

Jo *_*Smo 2 c# asp.net-mvc entity-framework

我想获取所有汽车,但只获取每辆车的最新报告,而不是所有卡片及其所有报告。一辆车可以有多个报告。

// with this i would get all cars with all reports for each car.
// How can i get all cars with only the last report for each car?
context.Cars.Include("Reports");
Run Code Online (Sandbox Code Playgroud)

我试过这样的事情:

context.Cars.Include(c => c.Reports.OrderByDescending(r => r.Id).FirstOrDefault())
.Take(10)
.ToList();
Run Code Online (Sandbox Code Playgroud)

但这没有用。

oct*_*ccl 6

我同意@GaryMcGill,Include扩展方法不允许您部分加载导航属性。您可以做的是改用显式加载

var car=yourPreviousQuery.FirstOrDefault(); // This is just an example to have a Car instance
context.Entry(car) 
    .Collection(b => b.Reports) 
    .Query().OrderByDescending(r => r.Id).Take(1) 
    .Load(); 
Run Code Online (Sandbox Code Playgroud)


Gen*_*e R 4

.Select(p => new
{
    Car = p,
    Report = p.Reports.OrderByDescending(r => r.Id).FirstOrDefault()
})
Run Code Online (Sandbox Code Playgroud)

这将给出一个匿名对象列表,您可以将其转换为IEnumerable<Cars>