当尝试解析不等式比较的列时,LINQ to Entities不会识别方法“Int32 Parse(System.String)”方法 [英] LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method when attempting to parse a column for inequality comparisons

查看:145
本文介绍了当尝试解析不等式比较的列时,LINQ to Entities不会识别方法“Int32 Parse(System.String)”方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

开始和结束都是int,但是 p.ID 是字符串。所以我应该将 p.ID 转换为int。但是我收到以下错误:


LINQ to Entities不识别方法'Int32
Parse(System.String)'方法,并且此方法无法将
转换为存储表达式。


问题在哪里? b $ b

解决方案

首先,我强烈建议检查您的数据库设计,是否有一个非常好的理由 ID 成为字符串。我会考虑将 ID DB类型更改为 int ,您将摆脱转换



您所得到的错误意味着,EF不知道如何转换方法 Int32.Parse()到SQL。
基本上你有两个选择如何处理:



在linq以外的实体进行比较:

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

但这是不推荐,因为您正在阅读整个结果集DB,然后再应用其中条件。



或使自定义模型定义函数为在这篇文章中描述的这个例子:



将字符串转换为EF 4.0中的Int $

实体框架:我在哪里扩展CSDL / MSL?


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

解决方案

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?

这篇关于当尝试解析不等式比较的列时,LINQ to Entities不会识别方法“Int32 Parse(System.String)”方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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