简体   繁体   中英

Does the order of the include and the where matter in a LINQ query?

I have the following:

var objectives = _objectivesRepository
                .GetAll()
                .Where(o => o.ExamId == examId || examId == 0)
                .Include(o => o.ObjectiveDetails)
                .ToList();

In a previous post one of the users said that it was important to put the where before the include in a LINQ query.

Can someone let me know if this is correct? Does order matter? How about if there are many where and includes ?

In Entity Framework yes it does matter, but only in certain scenarios. When using groupings or projections, it will fail to include the requested data.

See this blog post on the subject.

The actual answer, is that usually, the order does not matter significantly . Following your example statement, I would describe the logical translational steps to a relational query:

  1. Get all objects, with all their properties (in relational algebra they are considered attributes)
  2. Restrict the retrieved rows based on your condition (( relational algebra projection operation )
  3. Restrict the attributes of the retrieved rows which are eagerly loaded ( relational algebra selection operation )

In your specific query, the steps 2 and 3 are interchangeable without altering the final outcome . As stated here , this is the default case. Nevertheless, even if the final outcome would not change, the performance could be significantly be affected. This is the reason for which the modern databases have query optimizers which create an execution plan to optimize the specific query.

Nevertheless, this is not always the case . So, I suppose that you could always find a case where the above do not apply. Regarding performance, no assumptions are safe. You should always measure things. You could always use the SQL Server profiler to see the translation of your linq to entities query to the final SQL query. Then you could use the SQL server tools (like the query analyzer ) to see the execution plan of the final SQL query.

Hope I helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM