I’m working on transforming some existing Linq to SQL into Compiled queries, in part using this helpful article as a guide.
Below is an example of one of my original statements:
private IQueryable<Widget> GetWidgetQuery()
{
return db.Widgets.Where(u => (!u.SomeField.HasValue || !u.SomeField.Value));
}
Here’s my attempt at creating a compiled query:
private static readonly Func<DBDataContext, IQueryable<Widget>> GetWidgetQuery =
CompiledQuery.Compile((DBDataContext db) =>
db.Widgets.Where(u => (!u.SomeField.HasValue || !u.SomeField.Value)));
I’m having some trouble visualizing the differences between the standard and compiled incarnations of this query. Assuming my syntax is proper, will the compiled query return the same data as the standard one, just with the advantages using Compiled queries provides?
Yes it will return the same data – the IQueryable<Widget> object – but unlike the first example, you’ll lose the benefits of the compiled query if you extend the query further.
You will need to pass the DBDataContext object when you call GetWidgetQuery().
Returns IQueryable<Widget>:
With LINQ to SQL, this loses the benefit of the compiled query by performing a LINQ query on the results: