views:

119

answers:

4

Using the Entity Framework, when one executes a query on lets say 2000 records requiring a groupby and some other calculations, does the query get executed on the server and only the results sent over to the client or is it all sent over to the client and then executed?

This using SQL Server.

I'm looking into this, as I'm going to be starting a project where there will be loads of queries required on a huge database and want to know if this will produce a significant load on the network, if using the Entity Framework.

A: 

It's always executed on SQL Server. This also means sometimes you have to change this:

from q in ctx.Bar
where q.Id == new Guid(someString)
select q

to

Guid g = new Guid(someString);
from q in ctx.Bar
where q.Id == g
select q

This is because the constructor call cannot be translated to SQL.

Sander Rijken
+1  A: 

well, i had the same question some time ago. basically: your linq-statement is converted to a sql-statement. however: some groups will get translated, others not - depending on how you write your statement.
so yes - both is possible

example:

var a = (from entity in myTable where entity.Property == 1 select entity).ToList();

versus

var a = (from entity in myTable.ToList() where entity.Property == 1 select entity).ToList();
Andreas Niedermair
calling `.ToList`, or something else that needs to get the results in order to complete, causes the query to be evaluated. Just like foreach-ing through an IEnumerable/IQueryable.
Sander Rijken
that was the point ... it's all about HOW you write your statement ... ;)
Andreas Niedermair
+2  A: 

Sql's groupby and linq's groupby return differently shaped results.

Sql's groupby returns keys and aggregates (no group members)

Linq's groupby returns keys and group members.

If you use those group members, they must be (re-)fetched by the grouping key. This can result in +1 database roundtrip per group.

David B
This can ruin your performance if you don't spot it.
ck
+1  A: 

I would think all database querying is done on the server side (where the database is!) and the results are passed over. However, in Linq you have what's known as Delayed Execution (lazily loaded) so your information isn't actually retrieved until you try to access it e.g. calling ToList() or accessing a property (related table).

You have the option to use the LoadWith to do eager loading if you require it.

So in terms of performance if you only really want to make 1 trip to the Database for your query (which has related tables) I would advise using the LoadWith options. However, it does really depend on the particular situation.

James
it's called deferred execution
Andreas Niedermair
I think it is commonly referred to as both...
James
Instead of using LoadWith, you can use projections. See http://stackoverflow.com/questions/1085462/conditional-include-in-linq-to-entities/1164175#1164175 for instance
Sander Rijken
@Sander, nice link +1
James