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

后端 未结 11 2220
花落未央
花落未央 2020-11-22 10:41

I\'m migrating some stuff from one mysql server to a sql server but i can\'t figure out how to make this code work:

using (var context = new Context())
{
            


        
11条回答
  •  眼角桃花
    2020-11-22 11:07

    Just save the string to a temp variable and then use that in your expression:

    var strItem = item.Key.ToString();
    
    IQueryable pages = from p in context.pages
                               where  p.Serial == strItem
                               select p;
    

    The problem arises because ToString() isn't really executed, it is turned into a MethodGroup and then parsed and translated to SQL. Since there is no ToString() equivalent, the expression fails.

    Note:

    Make sure you also check out Alex's answer regarding the SqlFunctions helper class that was added later. In many cases it can eliminate the need for the temporary variable.

提交回复
热议问题