我正在将一些东西从一个 mysql 服务器迁移到一个 sql 服务器,但我不知道如何使这段代码工作:
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)
时会抛出异常:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
有人知道为什么会这样吗?
最佳答案
只需将字符串保存到临时变量中,然后在您的表达式中使用它:
var strItem = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
where p.Serial == strItem
select p;
问题出现是因为 ToString()
没有真正执行,它变成了 MethodGroup然后解析并翻译成SQL。由于没有 ToString()
等效项,因此表达式失败。
注意:
确保您还查看了 Alex's answer关于稍后添加的 SqlFunctions
辅助类。在许多情况下,它可以消除对临时变量的需要。
关于c# - LINQ to Entities 无法识别方法 'System.String ToString()' 方法,并且该方法无法转换为存储表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5899683/