1

I know that Entity Framework queries can't contain arrays. For example, this will fail:

var myRow = DbContext.myTable.Single(d => d.Property1 == myArray[0].Property1);

But if I assign that element into a variable first like this:

var property1 = myArray[0].Property1;
var myRow = DbContext.myTable.Single(d => d.Property1 == property1);

Then it works. Why can't the compiler do this for us? It already makes optimizations and affords us shortcuts via syntactic sugar in many other circumstances. Is there a source of ambiguity that would prevent the compiler from copying the array element into a temporary variable in the background? Or some other reason?

3
  • It's not a limitation of the the C# compiler but with the Linq to Entities provider. Commented Jun 21, 2016 at 16:33
  • 1
    Because in your second piece of code you are working with a constant value, which in turn can be part of the expression. Your linq in the first piece of code cannot be converted to an expression. Commented Jun 21, 2016 at 16:33
  • There are many similar (not exactly duplicates) discussions about almost each particular method/property that does not get translated to SQL by LINQ-to-EF/LINQ-to-SQL providers. I.e. stackoverflow.com/questions/3360772/… has good links to other discussions. Commented Jun 21, 2016 at 16:38

1 Answer 1

3

Linq-to-objects can handle that just fine - It's linq-to-EF (or Linq-to-SQL) that will try to convert the expression into SQL. Putting the value in a variable tells the provider that you want to use the value, not evaluate the expression.

Why can't the compiler do this for us?

Because the compiler has not been programmed to distinguish between expressions that should be translated to SQL and those that should be evaluated before the query is compiled.

Linq queries use deferred execution, meaning that the query is not actually executed until you ask for the results. Until then it's just a query made up of individual expressions that make up the filters, projections, groupings, aggregations, etc. When it evaluates the expression d => d.Property1 == myArray[0].Property1 it does not evaluate the expression at that time, so when the provider gets to it, it tries to convert it to SQL, which it cannot do.

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

1 Comment

And because compiler can't distinguish between Expression Tree that will be executed synchronously (thus possibly converting indexed access to result of it) vs. asynchronously (when element at given index can change multiple times before expression is evaluated).

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.