LINQ to SQL *compiled* queries and when they execute

Viewed 2112

I have the following compiled query.

private static Func<Db, int, IQueryable<Item>> func =
        CompiledQuery.Compile((Db db, int id) => 
            from i in db.Items
            where i.ID == id
            select i
            );

This executes on the database immediately when I do

var db = new Db()
var query = func(db, 5);  // Query hits the database here

As in before doing

var result = query.SingleOrDefault(); // Happens in memory

But if this query wasn't compiled, as in

var query = from i in db.Items
            where i.ID == id
            select i

then it executes on the database after doing

   var result = query.SingleOrDefault();

Is this the expected behaviour?

Note: This is a duplicate of When does a compiled query that returns an IQueryable execute?, but all the answers on there seem to disagree with my findings. I have posted my answer there, but I don't know how to get peoples' attention to it as it's over 2 years old.

3 Answers
Related