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;
}

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thought as much but that means I'm going to be writing one very long and confusing looking query. Many thanks.
Proper line breaks and indenting will help out a lot.
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).
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.