Paul
Paul

Reputation: 1159

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

Upvotes: 3

Views: 1672

Answers (1)

Sam Holder
Sam Holder

Reputation: 32936

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

Upvotes: 2

Related Questions