Reputation: 1207
I have the following two models:
public class Customer
{
public string CustomerNumber { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual Order LastOrder { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
public class Order
{
public string OrderNumber { get; }
public decimal Total { get; set; }
public DateTime Date { get; set; }
public virtual Customer Customer { get; set; }
}
And here is the point: Sometimes i want all orders included then i will load it with
db.Customers.include(c => c.Orders)
LastOrder { get => Orders.FirstOrDefault() }
But sometimes i dont want to load all, because in a overtable or something liek that i dont need all.
But still i want to load the "LastOrder" is it possible to bind that property to a subquery? So that there is a query fired like:
Select *
From Orders
Where CustomerId = 3
OrderBy Date
Limit 1
Upvotes: 1
Views: 265
Reputation: 142018
You can use filtered include (available since EF Core 5, check out the docs to understand limitations and possible issues):
var result = db.Customers
.Include(d => d.Orders.OrderByDescending(o => o.Date).Take(1))
// ... rest of the query
.ToList();
Upvotes: 1