mike oconner
mike oconner

Reputation: 69

Order by one to many FK in Entity Framework

I have a class with a list that stores a list of dates for an event, and I need to query for the list of events and order them by the dates, how can I achieve this in Entity Framework.

This is my main class

public class UserEv
{
    public string title { get; set; }
    public virtual List<Dates> dates { get; set; }
}

I need to query for the dates available in this class

public class Dates
{
    public DateTime start { get; set; }
    public DateTime end { get; set; }
}

I need to order the results that I get from the query by the start date. How can I achieve this in EF.This is the current query I use to get the data from the db, I am having trouble on the ordering part.

db.UserEv.Where(l=> l.dates.Any(a => a.start>= (start)))
         .Where(l=> l.dates.Any(b => b.end<= (end)))

Any help would be great.

Upvotes: 0

Views: 54

Answers (1)

Steve Py
Steve Py

Reputation: 34673

Assuming this works:

db.UserEv.Where(l=> l.dates.Any(a => a.start>= (start)))
     .Where(l=> l.dates.Any(b => b.end<= (end)))

To sort by the earliest start date:

.OrderBy(l => l.Dates.Min(d => d.start));

Upvotes: 3

Related Questions