我想知道编写这样的查询的正确方法:
var questions = from q in db.Questions
join sq in db.SurveyQuestions on q.QuestionID = sq.QuestionID
where sq.SurveyID == 1
orderby sq.Order
select q;
我基本上想从问题表中选择与不同表中的值匹配的所有内容。
我认为也可以这样写查询:
var questions = from q in db.Questions
from sq in q.SurveyQuestions
where sq.SurveyID == 1
orderby sq.Order
select q;
这个查询不起作用,但更符合我的想法:
var questions = from q in db.Questions
where q.SurveyQuestions.SurveyID == 1
orderby q.SurveyQuestions.Order
select q;
使用导航属性在 Entity Framework 中编写这些类型的查询的正确方法是什么?
请您参考如下方法:
还没有测试过这个,但我想这就是你要找的
var questions = from sq in db.SurveyQuestions
where sq.SurveyID == 1
orderby sq.Order
select sq.Question;
其中 Question 是 SurveyQuestion 的导航属性。
您正在使用实体而不是数据库表。这种类型的查询正是 EF 所关注的。您不必像在第一个查询中那样考虑数据库表。相反,您可以立即开始过滤 SurveyQuestions,这样更直观。如果您直接在数据库上操作,导航属性将抽象出您将使用的连接。
