It is preferable to utilize Entity Framework. First() or . For "TOP 1," how about (1)?

entity-framework ienumerable linq linq-to-objects sql

Question

EF data repositories are being implemented, and we have several queries that would involveTOP 1

I've seen several postings that recommend using.Take(1)
The code I'm examining utilizes.First()

I am aware that both of these provide the same outcome for object assignment, but do they both go to the same query in reality? Will the DB truly be consulted when a query is made?TOP 1 to both inquiries? Or will they just grab the first item in the collection after fully executing the query into the enumerable?

Additionally, if we applied.FirstOrDefault() So why should we anticipate any other behavior? I am aware that invoking an IEnumerable.First() throwing will occur on an empty collection, however if this is merely altering the query to includeTOP 1 thus there should be no functional difference at all between.First() and .FirstOrDefault() .... right?

Alternatively, is there a more effective way to make the query run than these Enumerable extensions?TOP 1 ?

1
39
5/4/2012 8:04:16 PM

Accepted Answer

zzz-5 to zzz:

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]

Observe thatTake(1) returns an after enumeratingIQueryable .

74
5/4/2012 8:19:40 PM

Popular Answer

See what query each option returns by redirecting the DataContext Log property to Console.Out or a TextFile.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow