5

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)
user1842278
  • 1,039
  • 1
  • 12
  • 25

2 Answers2

4

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

Community
  • 1
  • 1
A.T.
  • 24,694
  • 8
  • 47
  • 65
1

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.

Michael Sander
  • 2,677
  • 23
  • 29
  • 1
    In an ideal world, and perhaps in most cases this is both entirely true and obviously the recommended answer. However, there are edge cases - http://bradsruminations.blogspot.no/2010/04/looking-under-hood.html – Lasse V. Karlsen Apr 24 '15 at 07:34
  • agreed, but you don't have this control from within the entity framework. you would need something like stored procedures or views and give the optimizer hints how to treat the statement – Michael Sander Apr 24 '15 at 07:40