Query a table by using foreign key navigation properties in LINQ with C#

你离开我真会死。 提交于 2019-12-11 15:15:07

问题


I have the following LINQ to SQL EF classes:

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:


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).



来源:https://stackoverflow.com/questions/6764013/query-a-table-by-using-foreign-key-navigation-properties-in-linq-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!