tett
tett

Reputation: 605

LINQ to Entities does not recognize the method 'Int32 ToInt32(System.String)' method

I checked online for some answers, and I understood that I cannot translate ToInt32 to T-SQL, and I need to use run my query in-memory first and then do the conversion, but I don't know how to apply it in my example. I have the query below, and it shows me the error message written in the title:

string[] parts = rvm.ZipCode.Split('-');
var list = results.OrderBy(b => 
  Math.Abs(Convert.ToInt32(parts[0]) - Convert.ToInt32(b.Zip))).Take(5).ToList();

Where results is another query that I applied earlier. Any idea how to solve it?

Upvotes: 0

Views: 740

Answers (3)

Christos
Christos

Reputation: 53958

You could try something like this:

// It would be better, if we make the conversion only once instead of 
// doing this each time we fetch an item from our collection.
int value = Convert.ToInt32(parts[0]);

var list = results.AsEnumerable()
                  .OrderBy(z => Math.Abs(value - Convert.ToInt32(z.Zip)))
                  .Take(5)
                  .ToList();

Upvotes: 1

MikeT
MikeT

Reputation: 5500

Linq2SQL and Linq2Entity always try and pass the query to the database and most databases don't have the same functionality as the convert class. this means that to apply the convert function you need to instruct linq to retrieve the data from the database so that it can run the code rather than just passing it to the database.

this is done by instantiating the query by calling AsEnumerable() or ToList() before you call the convert function

the other option would be to change it to a simpler convert such as (int) or as int? as these do have a direct database mapping

Upvotes: 0

Coding Flow
Coding Flow

Reputation: 21881

Calling AsEnumerable() will force it to do the ordering in memory:

var list = results.AsEnumerable().OrderBy(b => Math.Abs(Convert.ToInt32(parts[0]) - Convert.ToInt32(b.Zip))).Take(5).ToList();

This may be extremely ineficient though as the Take(5) will occur after the data has already been retrieved from the database, so you are fetching the entire result set into memory, sorting it an then discarding all but the top 5 records.

Upvotes: 2

Related Questions