简体   繁体   中英

EF Core 5, Order Entities by date in child collection

I have a simple relation like

public class Invoice{
  public int Id {get;set;}
  ICollection Product Products {get;set;}
}

public class Product {
  public int Id {get;set;}
  public DateTime ReceptionDate {get;set;}
  public virtual Invoice Invoice{get;set;}
}

I want to present invoices ordered by Product ReceptionDate, so the invoice with the most recent Product goes first. I'm also paging the results.

I tried

invoices.OrderByDescending(x => x.Products.Select(y => y.ReceptionDate)).Skip(x).Take(y);

But it's not even a valid query.

Could not find a similar question by searching.

Thanks.

Edit: Also tried Sergey solution but it's too slow, because it calls ToArray() fetching thousands of records from the database.

Try this query:

var query=Products
    .GroupBy(g => new { g.Invoice.Id, g.ReceptionDate})
    .Select(g => new 
        {
           Id=g.Key.Id
           ReceptionDate=g.Key.ReceptionDate
        })
    .OrderBy(x => x.ReceptionDate)
    .ToArray();

Maybe you should try this:

invoices.OrderByDescending(x => x.Products.Max(y => y.ReceptionDate));

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