I am running into a problem with a LINQ query. I have the following data structure (Entity Framework classes mapped to a SQL Server DB):
Event has an EventBlocks property with 0 or more EventBlock objects as children. EventBlock has a Details property with 0 or more EventBlockDetail objects as children. EventBlockDetail has a DetailDate and a StartTime.
I need to show the next 3 upcoming events on a website. Sort order is determined by the event's earliest start date and time, which is stored in Event -> EventBlock -> EventBlockDetail. If the next 2 or 3 upcoming EventBlockDetails happen to belong to the same event, that event should only be shown once, and another event should show up in the top 3.
Is there any way to accomplish this with a single LINQ query, so I won't have to do a lot of looping and comparing after getting ALL the event data from the database?
To illustrate what I am trying to do, here is a fictitious query, which will obviously not work because the first OrderBy doesn't know which property to order by.
var result = this.Context.Events.Where(
e => e.WebsiteId == websiteId &&
e.EventBlocks.All(
b => b.Details.All(
d => d.DetailDate >= DateTime.Now
)
)
).OrderBy(
e => e.EventBlocks.OrderBy(
b => eb.Details.Min(d => d.DetailDate)).ThenBy(
b => eb.Details.Min(d => d.StartTime))
).Take(nrOfEvents).ToList();
DetailDate
and theStartTime
?