LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法无法转换为存储表达式 [英] LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

查看:23
本文介绍了LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法无法转换为存储表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些东西从一台 mysql 服务器迁移到一台 sql 服务器,但我不知道如何使这段代码工作:

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())
{
    ...

    foreach (var item in collection)
    {
        IQueryable<entity> pages = from p in context.pages
                                   where  p.Serial == item.Key.ToString()
                                   select p;
        foreach (var page in pages)
        {
            DataManager.AddPageToDocument(page, item.Value);
        }
    }

    Console.WriteLine("Done!");
    Console.Read();
}

当它进入第二个 foreach (var page in pages) 时,它抛出一个异常说:

When it enters into the second foreach (var page in pages) it throws an exception saying:

LINQ to Entities 无法识别方法System.String"ToString()' 方法,且此方法无法转为 store表达.

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

有人知道为什么会这样吗?

Anyone know why this happens?

推荐答案

只需将字符串保存到临时变量中,然后在您的表达式中使用它:

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

var strItem = item.Key.ToString();

IQueryable<entity> pages = from p in context.pages
                           where  p.Serial == strItem
                           select p;

问题出现是因为ToString()没有真正执行,而是变成了MethodGroup 然后解析并翻译成 SQL.由于没有 ToString() 等价物,表达式失败.

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.

确保您还查看了 Alex 的回答 关于稍后添加的 SqlFunctions 帮助程序类.在很多情况下,它可以消除对临时变量的需要.

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.

这篇关于LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且此方法无法转换为存储表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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