对于Entity Framework,是否最好将.First()或.Take(1)用于"TOP 1"? [英] With Entity Framework is it better to use .First() or .Take(1) for "TOP 1"?

查看:73
本文介绍了对于Entity Framework,是否最好将.First()或.Take(1)用于"TOP 1"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在实现一些EF数据存储库,并且我们有一些查询,其中包括TOP 1

We are implementing some EF data repositories, and we have some queries which would include TOP 1

我读了很多建议使用.Take(1)的帖子
我正在查看的代码使用.First()

I have read many posts suggesting to use .Take(1)
The code I'm reviewing uses .First()

我知道这两种对象分配都产生相同的结果,但是它们实际上都解析为同一查询吗?当查询数据库时,两个请求实际上都使用TOP 1吗?还是他们将查询完全执行到可枚举中,然后简单地将集合中的第一个条目录入?

I understand that both of these produce the same result for the object assignment, but do they both actually resolve to the same query? When the DB is queried, will it actually be with TOP 1 for both requests? Or will they execute the query in full into the enumerable, then simply take the first entry in the collection?

此外,如果我们使用.FirstOrDefault(),那么为什么我们应该期待任何不同的行为?我知道使用IEnumerable时,将在空集合上调用.First(),但是如果此实际上仅将查询更改为包括TOP 1,那么我应该期望.First().FirstOrDefault() ....对吗?

Furthermore, if we used .FirstOrDefault() then why should we expect any different behavior? I know that when using an IEnumerable, calling .First() on an empty collection will throw, but if this is actually only changing the query to include TOP 1 then I should expect absolutely no functional difference between .First() and .FirstOrDefault().... right?

或者,有没有比这些可枚举范围更好的方法来使查询执行TOP 1?

Alternatively, is there some better method than these Enumerable extentions for making the query execute TOP 1?

推荐答案

来自 LINQPad :

C#:

age_Centers.Select(c => c.Id).First();
age_Centers.Select(c => c.Id).FirstOrDefault();
age_Centers.Select(c => c.Id).Take(1).Dump();

SQL :

SELECT TOP (1) [t0].[Id]
FROM [age_Centers] AS [t0]
GO

SELECT TOP (1) [t0].[Id]
FROM [age_Centers] AS [t0]
GO

SELECT TOP (1) [t0].[Id]
FROM [age_Centers] AS [t0]

*请注意,Take(1)枚举并返回IQueryable.

*Note that Take(1) enumerates and returns an IQueryable.

这篇关于对于Entity Framework,是否最好将.First()或.Take(1)用于"TOP 1"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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