Wriju's BLOG

.NET, Cloud and everything

LINQ to SQL : Understanding Compiled Query

Understanding Compiled Query connects me to my experience in C# 3.0. Based on my personal understanding I am discussing it.


You may be aware of Func<>. And you know it is a flexible delegate which allows you create reusable functions. Exactly the same way we can create compiled query so that we can prevent the Expression Compilation during runtime.


Let us first understand how Func works.


You create a Func for square and use it anywhere in your application


Func<double, double> sqr = x => x * x;




This is precompiled and works just like a variable. So the magic is you declaring a reusable function as variable.


Now assume that it is in form of expression. Things works differently


//Wrap it with Expression<>

Expression<Func<double, double>> sqr = x => x * x;


//Expression cannot be executed but can be viewed



//Make it executable you need to call Compile()

var mySqr = sqr.Compile();


//Now this becomes executable



So every time you need to call this function you need to call Compile() or at least once.


This works exactly same in LINQ to SQL in Compiled Query. Now notice this below Compiled Query.



Func<NWDataContext, string, IQueryable<Customer>> q =

    CompiledQuery.Compile<NWDataContext, string, IQueryable<Customer>>

        ((NWDataContext nw, string sCity) =>

            from o in nw.Customers

            where o.City == sCity

            select o);

It is doing nothing but creating Func for your LINQ to SQL.


using (NWDataContext db = new NWDataContext())


    foreach (Customer c in q(db, “London”))






It is very powerful and performance effective.