为什么LINQ to Entities无法识别某些方法? [英] Why do LINQ to Entities does not recognize certain Methods?

查看:63
本文介绍了为什么LINQ to Entities无法识别某些方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能这样做:

usuariosEntities usersDB = new usuariosEntities();      
foreach (DataGridViewRow user in dgvUsuarios.Rows)
{
   var rowtoupdate = 
       usersDB.usuarios.Where(
       u => u.codigo_usuario == Convert.ToInt32(user.Cells[0].Value)
       ).First();
   rowtoupdate.password = user.Cells[3].Value.ToString();
}
usersDB.SaveChanges();

并且必须这样做:

usuariosEntities usersDB = new usuariosEntities();      
foreach (DataGridViewRow user in dgvUsuarios.Rows)
{
   int usercode = Convert.ToInt32(user.Cells[0].Value);
   var rowtoupdate = 
       usersDB.usuarios.Where(u => u.codigo_usuario == usercode).First();
   rowtoupdate.password = user.Cells[3].Value.ToString();
}
usersDB.SaveChanges();

我必须承认这是一个更具可读性的代码,但是为什么不能这样做呢?

I must admit it is a more readable code but why cant this be done?

推荐答案

关于它的事情是LINQ查询由编译器转换为表达式树.然后将该表达式树转换为T-SQL并传递给服务器. LINQ to SQL映射某些方法,例如String.包含T-SQL等效项.

The thing about it is that LINQ queries are transformed by the compiler into an expression tree. This expression tree is then converted into T-SQL and passed to the server. LINQ to SQL maps certain methods like String.Contains to the T-SQL equivalents.

在第一个示例中,LINQ显然没有将Convert.ToInt32映射到任何东西,并且引发了异常.它在第二个示例中起作用的原因是因为在查询的外部中完成了Convert.ToInt32调用,因此它不是表达式树的一部分,不需要转换为T-SQL

In the first example, LINQ apparently does not map Convert.ToInt32 to anything and the exception is thrown. The reason it works in your second example is because the Convert.ToInt32 call is done outside of the query so it isn't part of the expression tree and doesn't need to be converted to T-SQL.

此MSDN页面描述LINQ to SQL的翻译方式T-SQL中的各种数据类型,运算符和方法. (尽管文档确实建议支持Convert.ToInt32,所以我不确定这里可能还会发生什么.)

This MSDN page describes how LINQ to SQL translates various data types, operators, and methods into T-SQL. (Although the documentation does suggest Convert.ToInt32 is supported so I'm not sure what else might be going on here.)

对不起,您刚刚意识到这是ADO.NET实体框架,而不是LINQ to SQL. 此页面列出了 ADO.NET实体框架映射.限制更多,主要是因为它需要与多个提供程序一起使用.

Sorry just realized this is ADO.NET Entity Framework, not LINQ to SQL. This page lists the ADO.NET Entity Framework mappings. It is a bit more restrictive, mostly because it needs to work with multiple providers.

这篇关于为什么LINQ to Entities无法识别某些方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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