views:

135

answers:

2

I'd like to see a basic and clear example of how to compile a LinQ to SQL query. I've googled about it, and even though there are a couple of implementation examples, usually blog posters emphasize on the time response difference between compiled and non-compiled queries.

+1  A: 

LINQ To SQL Compiled Queries basically allow that the translation of LinqToSQL query to plain SQL, happen only once at compile time so the query can be re-used without performing any translation.

They are represented as static Func delegates, receiving a DataContext instance and parameters that will be used in the query:

public static Func<MyDataContext, string, IQueryable<Entity>>
    TestQuery =
        CompiledQuery.Compile((MyDataContext ctx, string param) =>
            from e in ctx.Entities where e.Field == param select e);

An usual practice is that compiled queries can be stored as static members on a partial class that extends the DataContext generated class.

CMS