Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do LINQ to Entities does not recognize certain Methods?

Why cant I do this:

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();

And have to do this:

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?

like image 716
Luiscencio Avatar asked Mar 17 '10 22:03

Luiscencio


1 Answers

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.

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.

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.)

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.

like image 162
Josh Avatar answered Nov 03 '22 09:11

Josh