开发者

EF OrderBy One to Many

开发者 https://www.devze.com 2023-03-06 07:21 出处:网络
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 q

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


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

精彩评论

暂无评论...
验证码 换一张
取 消