LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method when attempting to parse a column for inequality comparisons

c# entity-framework

Question

I have following code in my page:

var myVar= Entity.SetName
                 .Where(p => int.Parse(p.ID) >= start &&
                  int.Parse(p.ID) <= end);

start and end are int, but p.ID is string. So i should convert p.ID to int. But i get following error:

LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression.

Where is the problem??

1
22
7/31/2015 5:35:01 PM

Accepted Answer

First, I would highly recommend to check your database design, whether there is a really good reason for ID to be a string. I would consider changing the ID DB type to int and you will get rid of this problem with converting.

The error you get means, that EF does not know how to convert the method Int32.Parse() to SQL. Basically you have two options how to deal with that:

Do the comparison outside the linq to entities:

var myVar= Entity.SetName.AsEnumerable()
                 .Where(p => int.Parse(p.ID) >= start &&
                  int.Parse(p.ID) <= end);

But this is not recommended, because you are reading whole result set from DB, before applying the where condition.

Or make custom model defined function as described in this post on SO:

Convert String to Int in EF 4.0 or Entity Framework: Where do I extend the CSDL/MSL?

15
5/23/2017 11:33:16 AM

Popular Answer

move the parse function out of linq expression.

int id = int.Parse(p.ID);
var myVar= Entity.SetName
.Where(p => id >= start && int.Parse(p.ID) <= end);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow