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?

Anthony Pegram
  • 123,721
  • 27
  • 225
  • 246
Legion
  • 3,922
  • 8
  • 51
  • 95
  • It's not a limitation of the the C# compiler but with the Linq to Entities provider. – p.s.w.g Jun 21 '16 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. – Stephen Brickner Jun 21 '16 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. http://stackoverflow.com/questions/3360772/linq-contains-case-insensitive has good links to other discussions. – Alexei Levenkov Jun 21 '16 at 16:38

1 Answers1

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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • 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). – Alexei Levenkov Jun 21 '16 at 16:42