Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF OrderBy One to Many

Okay, I have a Person entity with a collection of Addresses. The Person may have zero or many addresses and those addresses have a rank (int). I want to be able to sort the results of a query by either the city or state of the lowest ranked address in the addresses collection. However the fact that the collection may be empty for some people is driving me crazy and I can't change it.

Something like this but without the exception when the address collection is empty

ctx.People
     .OrderBy(p => p.Addresses
                       .OrderBy(a => a.Rank)
                       .First().City);
like image 842
Paul Avatar asked Nov 18 '25 22:11

Paul


1 Answers

don't you want to only include people who have addresses then? otherwise how can the orderby be done?

something like this untested code:

ctx.People
 .Where(p=>p.Addresses.Any())
 .OrderBy(p => p.Addresses
                   .OrderBy(a => a.Rank)
                   .First().City);

EDIT

I'll be getting out of my linq depth here I'm sure (I've not used union before just guessing from the docs) but if you want people with no address also included don't you want something along these lines:

ctx.People
 .Where(p=>p.Addresses.Any())
 .OrderBy(p => p.Addresses
                   .OrderBy(a => a.Rank)
                   .First().City)
 .Union(
    ctx.People
    .Where(p=>p.Addresses.Any()==false));
like image 104
Sam Holder Avatar answered Nov 20 '25 16:11

Sam Holder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!