Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

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

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??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...