Query a table by using foreign key navigation prop

2019-09-09 05:30发布

I have the following LINQ to SQL EF classes:

LINQtoSQL EF class diagram

with the foreign key relationship on SessionId (primary table WebinarSession).

I would like, by using lambdas to select all the WebinarSession rows that concern a specific product line.

I put as example this code that of course DOES NOT WORK(it would owrk with Single inseatd of Where but it is not applicable because I have mulitple instances matching the condition):

SessionId = _webinarRecordingsDB.WebinarSessions.Where(m => m.SessionId == m.SessionSubjects.Where(n => n.ProductLineName == productLine).SessionId);

Where _webinarRecordingsDB is the EF object mapping the SQL Database.

Does anybody know how to fulfill this task? Thanks

1条回答
爷、活的狠高调
2楼-- · 2019-09-09 06:14

This should do the trick:

var sessions = _webinarRecordingsDB.WebinarSessions.Where(w => w.SessionSubjects.Any(s => s.ProductLine == productLine));

When you define a foreign key in EF (or Linq to SQL classes) the designer should automatically create a property which would allow you direct access to the table from your entity (in your case your WebinarSession object should have a property called SessionSubjects).

查看更多
登录 后发表回答