I have a big LINQ query that results in inefficient SQL queries. I'm pretty sure I can optimize it a lot by shaping the query (like mentioned in this blog post by Scott Gu and also in this excellent blog post by Eugene Prystupa, who calls it "hinting").
However, this query is important legacy code, so I'd rather not touch the query itself. Is it possible to shape a LINQ query by modifying the resulting IQueryable?
For example, let's say the inefficient query is in GetOrders
, which returns the query result as an IQueryable<Order>
. Can I shape the IQueryable result? E.g.:
var result = GetOrders();
result = result.Select(o =>
new { o, o.Id, o.Customer, o.Payment })
.AsEnumerable()
.Select(o => o.o);
Note the Select at the end, which is to get back Order
objects. (See Prystupa's blog for this gem.) The point of this example shaping would be to get LINQ2SQL (or Entity Framework) to join the Order table with Customer and Payment. The original query would query those tables n
times after querying Order, where n
is the number of Orders.