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

查看:71
本文介绍了为什么我们不能在实体框架查询中使用数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Entity Framework查询不能包含数组.例如,这将失败:

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可以很好地处理-linq-to-EF(或Linq-to-SQL)将尝试将表达式转换为SQL.将值放在变量中会告知提供者您要使用该值,而不是对表达式求值.

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?

因为尚未对编译器进行编程,以区分应转换为SQL的表达式和应在编译查询之前对其求值的表达式.

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查询使用延迟执行,这意味着直到您要求查询结果时,该查询才真正执行.在此之前,这只是一个由构成过滤器,投影,分组,集合等的单个表达式组成的查询.当它评估表达式d => d.Property1 == myArray[0].Property1时,它会评估该表达式,因此,当提供程序使用它时,它将尝试将其转换为SQL,这是做不到的.

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.

这篇关于为什么我们不能在实体框架查询中使用数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆