为什么我们不能在实体框架查询中使用数组?[英] Why can't we use arrays in Entity Framework queries?

本文是小编为大家收集整理的关于为什么我们不能在实体框架查询中使用数组?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我知道实体框架查询不能包含数组.例如,这将失败:

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

但是,如果我首先将该元素分配给一个变量:

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

然后起作用.编译器为什么不能为我们做这件事?在许多其他情况下,它已经进行了优化,并通过句法糖提供了捷径.是否有歧义来源可以防止编译器将数组元素复制到后台的临时变量中?或其他一些原因?

推荐答案

linq-to-objects可以很好地处理这一点 - 它是Linq-to-ef(或Linq-to-SQL),它将尝试将表达式转换为SQL.将值放入变量中告诉提供商您要使用该值,而不是评估表达式.

编译器为什么不能为我们做这个?

由于尚未对编译器进行编程以区分应将其转换为SQL的表达式以及在查询之前应评估的表达式.

linq Queries使用延期执行,这意味着在您要求结果之前,该查询实际上未被执行.在此之前,它只是由单个表达式组成的查询,这些表达式构成了过滤器,投影,分组,聚合等.因此,当提供商获得它时,它试图将其转换为SQL,它无法做到.

本文地址:https://www.itbaoku.cn/post/1557032.html

问题描述

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?

推荐答案

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.