How do i sort my events with regards to “grandchildren's” date

末鹿安然 提交于 2021-01-29 08:05:22

问题


We’ve got an EF6 MVC3 codeFirst-site. Our Events may have a collection of EventRallies. And the EventRallies may have a collection of EventOccasions

I want to order them so that events with any future occasions is at the top, followed by events where all occasions are in the past, and then events that doesn´t have any rallies or occasinons tied to them.

The following attempt results in an :System.ArgumentException: DbSortClause expressions must have a type that is order comparable- error ;)

return context.Events.Where(x => x.OrganizationId == id).
Include(x => x.EventRallies).
Include(x => x.EventRallies.Select(e => e.EventOccasions)).
OrderBy(x => x.EventRallies.OrderByDescending(d=>d.EventOccasions.FirstOrDefault().Date)).ToList();

Any suggestions?


回答1:


You need SelectMany to get one list of all EventOccasions of one Event. Select their dates. This list can be ordered by date (descending). The first date in this list is the ordering key for the Events.

If you order by this date key descending, the future events will come first, then the past events, followed by the events without any occasion.

context.Events.Where(x => x.OrganizationId == id)
.Include(x => x.EventRallies)
.Include(x => x.EventRallies.Select(e => e.EventOccasions))
.OrderByDescending(x => x.EventRallies.SelectMany(d => d.EventOccasions)
    .Select(occ => occ.Date)
    .OrderByDescending(d => d)
    .FirstOrDefault()).ToList();


来源:https://stackoverflow.com/questions/62514712/how-do-i-sort-my-events-with-regards-to-grandchildrens-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!