Return single row in an EF-generated class with its children set ordered in LinqToSql (c#)
I would like to make a simple operation with LinqToSql but I cannot find the right way. I have the following tables, hereby represented with an EF-generated class diagram:
Where the foreign key relationship is on SessionId (primary key table WebinarSession).
I want to make a query that returns 1 WebinarSession with its corresponding children on WebinarTopic, ORDERED by TopicStartTime.
Taking into account that _webinarRecordingsDB is the repository object, I already tried the solutions that looked more logic to me:
WebinarSession lsession = _webinarRecordingsDB.WebinarTopics
.OrderBy(m => m.TopicStartTime)
.Select(m => m.WebinarSession)
.Single(m => m.SessionId == sessionId);
WebinarSession lsession = _webinarRecordingsDB.WebinarSessions
.Single(m => m.SessionId == sessionId).WebinarTopics
.OrderBy(m => m.TopicStartTime)
.Single(m => m.WebinarSession.SessionId == sessionId);
Those launch an exception because they find more rows in WebinarSession. As last (illogical) resort I also tried:
WebinarSession lsession = _webinarRecordingsDB.WebinarSessions
.Single(m => m.SessionId == sessionId);
lsession.WebinarTopics.OrderBy(m => m.TopicStartTime);
that does not launch any ex开发者_如何学Cception but does not perfor the sorting on lsession. Anybody might help me please? Thanks
EDIT
I want to keep the result in a WebinarSession object
The OrderBy
extension method does not does change the collection, but returns a new (ordered) collection. You need to store the results in a variable and use that:
var session = _webinarRecordingsDB.WebinarSessions
.Single(m => m.SessionId == sessionId);
var topics = session.WebinarTopics.OrderBy(m => m.TopicStartTime);
The Second Option is close, but you have to assign the sorted WebinarTopics back to a new IList or something, such as the following...
WebinarSession lsession = _webinarRecordingsDB.WebinarSessions.Single(m => m.SessionId == sessionId);
List<WebinarTopic> ltopics = lsession.WebinarTopics.OrderBy(m => m.TopicStartTime).ToList();
HTH. Dave
精彩评论