LINQ to Entities无法识别方法'System.Object Parse(System.Type, System.String)'。

6

我遇到了这个错误,尝试了很长时间但没有解决。

LINQ to Entities不识别'System.Object Parse(System.Type, System.String)'方法,因此无法将此方法翻译为存储表达式。

 public static List<itmCustomization> GetAllProductCustomziation(string catID)
            {
                var arrcatID = catID.Split('_');
                int PId = int.Parse(arrcatID[0].ToString());
                int CatID = int.Parse(arrcatID[1].ToString());
                EposWebOrderEntities db = new EposWebOrderEntities();
                List<itmCustomization> lstCust = new List<itmCustomization>();
                lstCust.AddRange((from xx in db.vw_AllCustomization
                                  where xx.CatID == CatID && xx.ProductID == PID
                                  select new itmCustomization()
                                  {
                                      itmName = xx.Description,
                                      catId = (int)xx.CatID,
                                      proId = (int)xx.ProductID,
                                      custType = (customizationType)Enum.Parse(typeof(customizationType), xx.CustType)
                                  }).ToList<itmCustomization>());
                return lstCust;

            }

EF的后续版本支持将枚举作为数据类型,因此xx.CustType可以是一个customizationType - Gert Arnold
2个回答

15

由于您正在使用LINQ To Entities,因此实体框架当前正在尝试将Enum.Parse转换为SQL,但它失败了,因为它不是受支持的函数。

您可以在调用Enum.Parse之前使您的SQL请求具体化:

lstCust.AddRange((from xx in db.vw_AllCustomization
                                  where xx.CatID == CatID && xx.ProductID == PID
                                  select xx)
                        .TolList()  // Moves to LINQ To Object here
                        .Select(xx => new itmCustomization()
                                  {
                                      itmName = xx.Description,
                                      catId = (int)xx.CatID,
                                      proId = (int)xx.ProductID,
                                      custType = (customizationType)Enum.Parse(typeof(customizationType), xx.CustType)
                                  }).ToList<itmCustomization>());

1
@NoviceToDotNet 我提供了一个修复它的示例代码。在使用 Enum.Parse 之前调用 ToList() 允许在 DB 服务器上执行 SQL 请求之后再执行它。 - ken2k

2

我认为这个错误是由custType = (customizationType)Enum.Parse(typeof(customizationType), xx.CustType)引起的。顺便问一下,xx.CustType的类型是什么?我觉得它返回的是一个字符串,但期望的类型是枚举类型,所以才会出现这个错误。


我在视图中添加了一列,像这样选择DressingID作为ID,Description,2作为CustType。 - NoviceToDotNet
1
尝试使用xx.CustType.ToString(),因为根据你的代码,CustType值为整数,而Enum.Parse函数期望第二个参数为字符串。即使这样做,它仍然会给出相同的错误,可能是由于LINQ不允许使用Enum.Parse。 - Nitin Joshi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接