Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does it matter which order I put conditions in Entity framework

Does it matter which order I put conditions in Entity framework? I know that EF does some optimizations before running the SQL query. So does it matter what condtion I put first?

For example ( just a subset of the real query in our application ). CaseNumber is a string and OrganizationId is a guid.

context.Evaluation.Where(e => e.Case.CaseNumber.Contains(inputModel.CaseNumber) && e.Case.OrganizationId == inputModel.OrganizationId)

Or

context.Evaluation.Where(e => e.Case.OrganizationId == inputModel.OrganizationId) && e.Case.CaseNumber.Contains(inputModel.CaseNumber)
like image 729
user1842278 Avatar asked Apr 24 '15 07:04

user1842278


2 Answers

MS Sql is advanced RDBMS and has its own execution plan for each query and cache that plan for successive queries that's the way it give you high performance.

Each lambda expression use in Entity framework is first converted to sql query and then optimized by the sql profiler, so it doesn't matter where you put conditions in lambda expression.

But if you still not getting desired performance and think sql execution plan is not upto the mark you can force the sql optimizer to use your defined execution plan.

you can read about that here. and you can follow same on stack overflow

like image 80
A.T. Avatar answered Oct 29 '22 16:10

A.T.


No, it does not matter. Any advanced database has an optimizer that will freely move around conditions, joins and anything else to optimize performance.

You should put them in a way that they are easy to read and understand by developers.

like image 40
Michael Sander Avatar answered Oct 29 '22 16:10

Michael Sander