ANURAG
ANURAG

Reputation: 5

Difference between lamda where condition and linq where condition?

I am working with MVC Core with EF-6.x and I am using Lambda expression, but my senior told me use LINQ why, because while using lambda with where clause it will pull all the data from database and later it will apply where condition. In case of LINQ if you use where condition it will pull only filtered data. Please let me know what is correct?

e.gLambda: context.tablename.where(condition);// Should I go with this

LINQ: (from T in tablename where t.(condition));// or this?

Upvotes: 0

Views: 254

Answers (3)

fededim
fededim

Reputation: 219

my senior told me use LINQ why, because while using lambda with where clause it will pull all the data from database and later it will apply where condition.

Your senior is wrong, you can use the statement you prefer they are the same, both will filter the data at database level. If you have Sql Server as database server, you can use Sql Server Profiler to dump the queries executed by both statements and you will see that they are the same.

Upvotes: 0

Aly Elhaddad
Aly Elhaddad

Reputation: 1953

Please let me know what is correct?

e.gLambda: context.tablename.where(condition);// Should I go with this

LINQ: (from T in tablename where t.(condition));// or this?

Short answer: it doesn't really matter. Since context.tablename ultimately returns an IQueryable<T>, Entityframework will not try to hit the database until you try to iterate the final result from your expression, not to mention, .ToArray() and .ToList() each, does that iteration for you.

Either you used LINQ expression syntax (which gets compiled as LINQ methods) or LINQ methods, when you attempt to begin iterating the results, Entityframework creates an Expression tree for you underneath the hood that consists of your query altogether (including Wheres, Joins, GroupBys, etc). Since the structure of a LINQ might not percisely match the structure of a SQL query (or whatever data-source query), depending on the source (i.e database, e.g SQL Server), Entityframework then attempts to make the best possible optimization to your expression tree so that its structure would match an executable query on the source (e.g SQL Server query). Finally, it translates that expression tree into an actual query and executes it against the data source, and return your data (after doing all the mapping of course).

If you really, and I mean REALLY want to go through the complications of how an IQueryable engine works, I'd suggest taking a walk through Matt Warren's series: 'LINQ: Building an IQueryable provider series'. That's not actually Entityframework but it shares the same concept.

Upvotes: 1

Oliver
Oliver

Reputation: 45119

Both syntax will be translated into the same IL code. The difference, if the filter will be applied on server or client side is, if the source is IQueryable<T> or IEnumerable<T>.

Upvotes: 1

Related Questions