views:

103

answers:

1

Why does this work ?

var x = from p in db.People let oCount = p.Orders.Count select p;

And not this ?

var x = from p in db.People let oCount = Count(p) select p;

private int Count(DataContext.Order o)
{
  return o.Count;
}
+4  A: 

LINQ to SQL "understands" p.Orders.Count, but it can't look inside your method to work out what it means - it could be doing anything as far as LINQ to SQL is concerned.

In your first query, p.Orders.Count is all represented in an expression tree which can be examined programmatically at execution time.

Jon Skeet
Thought as much but that means I'm going to be writing one very long and confusing looking query. Many thanks.
Chris Porter
Proper line breaks and indenting will help out a lot.
tvanfosson
As well as separating it out into multiple statements/queries (since the execution is delayed, you can split it out into multiple statements without hitting the database until you need to use the query results).
bdukes
This isn't even LINQ to SQL specific - in the first case the compiler produces an expression tree that a LINQ provider can translate. In the second case it produces the Count part as IL which would require runtime reverse-engineering/decompilation before it could try and figure out what was going on and translate it.
DamienG