C#linq在前后包含位置 [英] C# linq include before-after where

查看:62
本文介绍了C#linq在前后包含位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在linq中有以下区别:

In linq is there a difference between:

EFDbContext _db = new EFDbContext();



  1)_db.UserQuizes
        .Where(uq => uq.UserId == currentUserId && uq.QuizId == quizId)
        .Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question)).First()

2)_db.UserQuizes
        .Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question))                          
        .Where(uq => uq.UserId == currentUserId && uq.QuizId == quizId).First()

   3)_db.UserQuizes
            .Include(qz => qz.Quiz.VerbalQuizes.Select(q => q.Question))
             First(uq => uq.UserId == currentUserId && uq.QuizId == quizId)

请注意,第一个查询使用的位置包括after(位置)之后和second(第二位置)之前,但结果相同.另外如何查看实际的sql查询?在这种情况下,性能是我的主要目标,我可以改善查询吗?我需要更改两个属性:UserQuizes属性和UserQuizes-> VerbalQuizes-> Question属性.

Notice that first query uses include after where and second before where, but result is the same. Also how to see actual sql query? In this particular case perfomance is my main goal, can i improve the query? i need to change two properties : UserQuizes property, and UserQuizes-> VerbalQuizes-> Question property.

最好将其分为两个查询或按原样使用

Would it be better to split up it two queries or use it like as it is

推荐答案

像您所示的那样,指令的排序通常不会对EF或LINQ to SQL产生影响.查询生成器将整个LINQ语句转换为抽象逻辑表示,然后另一遍将逻辑结构转换为SQL语句.因此,WHERE谓词都将在同一位置结束. First()中的谓词只是被推到WHERE子句. Include语句也会被累积并投影到JOIN,以包括生成所包含实体所需的额外列.

Ordering of instructions like you've shown often won't make a difference in EF or LINQ to SQL. The query builder turns your entire LINQ statement into an abstract logical representation, and then another pass converts the logical structure into a SQL statement. So the WHERE predicates are all going to end up in the same place. The predicates inside a First() just get pushed over to the WHERE clause. The Include statements also get accumulated and projected to JOINs to include the extra columns needed to produce the included entity.

因此,简单的答案是,无论您构造LINQ语句的顺序如何,EF通常都会 产生最逻辑的SQL语句.如果需要进一步调整,则应查看一个存储过程,您可以在其中手工编写SQL.

So the short answer is that EF will usually produce the most logical SQL statement regardless of the order in which you constructed your LINQ statement. If you need to tune it further, you should look at a stored procedure where you can hand-craft the SQL.

这篇关于C#linq在前后包含位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆