6

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)
3
  • 2
    Please check this stackoverflow.com/a/1458072/311255
    – SelvaS
    Apr 24, 2015 at 7:26
  • 3
    Given that SQL has no guarantees when it comes to evaluation order (it's free to move predicates around), I'd doubt it. Apr 24, 2015 at 7:26
  • As long as the conditions are commutative, you're fine. Just be careful around brackets :))
    – Luaan
    Apr 24, 2015 at 7:38

2 Answers 2

5

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

2

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.

2
  • 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 - bradsruminations.blogspot.no/2010/04/looking-under-hood.html Apr 24, 2015 at 7: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 Apr 24, 2015 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.