在尝试解析列以进行不等式比较时,LINQ to Entities无法识别方法’Int32 Parse(System.String)’方法

我的页面中有以下代码:

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

start和end是int,但p.ID是string。 所以我应该将p.ID转换为int。 但我得到以下错误:

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

问题出在哪儿??

首先,我强烈建议检查您的数据库设计,是否有一个非常好的理由将ID作为string 我会考虑将ID DB类型更改为int ,您将通过转换摆脱这个问题

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

在linq之外进行实体比较:

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

但是不建议这样做 ,因为在应用where条件之前,您正在从DB读取整个结果集。

或者按照 SO上这篇文章中的描述制作自定义模型定义函数

在EF 4.0或entity framework 中将字符串转换为Int :我在哪里扩展CSDL / MSL?

将解析函数移出linq表达式。

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

首先尝试转换为int然后传递该变量名称

 int catgry = Convert.ToInt32(customercategory.OWNERSHIP_TYPE); var customerCateg = (from d in _db.tbl_SIL_CUSTOMER_CATEGORY_MST .Where(d => d.CAT_ID == catgry) select d.CAT_TYPE).SingleOrDefault(); 
 private void LoadDetail(int id) { var sp = from category in db.ProductCategories join product in db.Products on category.ProductCategoryID equals product.ProductCategoryID where id == int.Parse(category.ProductCategoryID) select new { product.ProductID, product.ProductName, product.ProductCode, product.Deception, category.CategoryName, product.Quanrity, product.Price }; DGVDetail.DataSource = sp.ToList();//help: Error: LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression } private void DGVMaster_CellClick(object sender, DataGridViewCellEventArgs e) { int index = e.RowIndex; LoadDetail(index + 1); } 

虽然效率不高,但您应该能够加载所有行,然后使用LINQ to Objects:

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