gpt4 book ai didi

c# - 编写 Entity Framework 查询的正确方法

转载 作者:太空宇宙 更新时间:2023-11-03 22:17:37 25 4
gpt4 key购买 nike

我想知道编写这样的查询的正确方法:

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;

其中 QuestionSurveyQuestion 的导航属性。

您正在使用实体而不是数据库表。这种类型的查询正是 EF 所关注的。您不必像在第一个查询中那样考虑数据库表。相反,您可以立即开始过滤 SurveyQuestions,这样更直观。如果您直接在数据库上操作,导航属性将抽象出您将使用的连接。

关于c# - 编写 Entity Framework 查询的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4474337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com