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

僤鯓⒐⒋嵵緔 提交于 2019-11-26 07:49:05

问题


I am using Entity Framework, and I have a line of code that is taking a var and translating it back to an iint for the database.

var record = context.enrollments.SingleOrDefault
  (row => row.userId == int.Parse(UserID) && row.classId == int.Parse(ClassID));

Whenever I try to run it I receive rhis error. \"LINQ to Entities does not recognize the method \'Int32 Parse(System.String)\' method, and this method cannot be translated into a store expression.\"

I have tried this as well

 var record = context.enrollments.FirstOrDefault
  (row => row.userId == Convert.ToInt32(UserID) 
  && row.classId == Convert.ToInt32(ClassID));

and all I receive is this error message, \"LINQ to Entities does not recognize the method \'Int32 ToInt32(System.String)\' method, and this method cannot be translated into a store expression

and finally I have tried this as well, which I know is unusual, but it has worked in the past for similar situations.

var record = context.enrollments.SingleOrDefault
  (row => row.userId == CommonDLL.Sanitize<int>.ConvertType(UserID) 
  && row.classId == CommonDLL.Sanitize<int>.ConvertType(ClassID));

In which I get this error. As you can see I have tried seveal different things and nothing is working, so any help would be great.


回答1:


in Linq to Entity, you should use the methods in your query which is supported by your provider to convert them to expression tree to run on your Data Base side.

all providers must support some methods by default called Canonical Functions (Read More Here), and also you can define your user defined function and stored procedure as edm functions to use in linq query (Read More Here) and (Here).

in addition you can use methods which is supported by providers and can be converted to expression tree which are in EntityFunctions and SqlFunctions.

and finally about your question, you can convert UserID and ClassID before your query, like this:

var UID = int.Parse(UserID);
var CID = int.Parse(ClassID);
var record = context.enrollments.SingleOrDefault
    (row => row.userId == UID && row.classId == CID);



回答2:


This works for me:

  var iId = int.Parse(TextBox1.Text);
 var item = db.Items.Where(p => p.ItemID == iId ).FirstOrDefault();

To make that work you should convert your textbox value outside of the lambda expression.



来源:https://stackoverflow.com/questions/23210526/linq-to-entities-does-not-recognize-the-method-int32-parsesystem-string-meth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!