问题
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 EventOccasion
s 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