9

Is there a difference in this code?

var query = DbContext.Customers
                .Where(<condition>)
                .Include("Address");

And

var query = DbContext.Customers
                .Include("Address")
                .Where(<condition>);

It's deffered query, and I don't know, is it equivalent? Or in the second case where is executed after Include?

Thanks.

Adel Khayata
  • 2,717
  • 10
  • 28
  • 46
Daniil Grankin
  • 3,841
  • 2
  • 29
  • 39

1 Answers1

5

For EF order prior to the select does not matter. The LINQ query is converted to a SQL query and run and the SQL query optimizer does not care about the order of the original query.

As Patryk pointed out order can matter specifically with Include when the following statements modify the structure of the query, but a where clause doesn't do that.

In other LINQ queries, LINQ-to-Objects, order can matter greatly as the query is not re-optimized the way SQL is and is simply processed from top to bottom, and some LINQ methods require previous methods to run to completion and process results before proceeding to even the first element (OrderBy for example).

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
  • In this case, yes. But that's not always true. Many queries are order dependent, particularly after a select. – Erik Funkenbusch Aug 09 '13 at 02:20
  • @MystereMan, good point about the select, I updated my answer to clarify that point. The key point is that not all LINQ is the same--LINQ to EF is different from LINQ to Objects and any other LINQ. LINQ to EF is mostly converted to SQL and mostly order does not matter. – Samuel Neff Aug 09 '13 at 02:34