问题描述
我想知道下一件事:
我可以使用LINQ To Entities查询数据库,如下所示:
I can query my database using LINQ To Entities, like this:
GetAll().Where(
x => x.SomeProperty == 'Yes'
&& x.SomeOtherProperty == 'No')
.ToList();
虽然我看到我的一些同事更改了这两个WHERE子句,例如:
While I see some of my colleagues change these two WHERE-clauses, like this:
GetAll().Where(x => x.SomeProperty == 'Yes')
.Where(x.SomeOtherProperty == 'No')
.ToList();
两个查询都应该产生相同的输出,但是我想知道两者之一是否有优点/缺点.例如,一种方法会产生较慢的数据库查询,还是会生成相同的sql查询?
Both queries should produce the same output, but I was wondering if one of the two has any advantages/disadvantages. For instance, does one method produce a slower database query, or would they generate the same sql-query?
推荐答案
我使用这篇文章,并按照问题中的模式记录了两个不同查询的SQL.我提出的查询是:
I set up a test project using the model and context described in this article and logged the SQL for two different queries, following the pattern in your question. The queries I made were:
db.Blogs
.Where(b => b.BlogId == 0)
.Where(b => b.Name == "Foo");
和
db.Blogs
.Where(b => b.BlogId == 0 && b.Name == "Foo");
两个查询生成的SQL是相同的:
The generated SQL for both queries is identical:
SELECT
[Extent1].[BlogId] AS [BlogId],
[Extent1].[Name] AS [Name]
FROM [dbo].[Blogs] AS [Extent1]
WHERE (0 = [Extent1].[BlogId]) AND (N'Foo' = [Extent1].[Name])
因此(至少对于这样的简单情况),似乎没有一种或另一种明显的性能差异.我猜您可能会争辩说,如果使用多重 Where
方法,则表达式访问者需要更长的时间来检查您的树,但是从长远来看,这可以忽略不计.
So it seems (at least for simple cases like this), there is no significant performance difference one way or the other. I guess you could argue it takes the expression visitor a bit longer to examine your tree if you use the multiple Where
approach, but this is negligible in the long run.
这篇关于LINQ:一个“在哪里"子句与多条链接的"where子句"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!