简体   繁体   中英

.NET 6 & EF Core 6: Subselect for one property

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM