/// <summary>
/// Get All Countries
/// </summary>
/// <returns></returns>
public IEnumerable<CountryVM> GetAllCountry( )
{
using (Context context = new Context() )
{
var countries = context.COUNTRY.Select(c => new CountryVM()
{
ID = c.ID,
DESCRIPTION = c.DESCRIPTION,
}
).ToList(); // Gets Exception here.
return countries;
}
为什么我无法转换为 ToList() ?
我得到以下异常:
LINQ to Entities does not recognize the method 'System.Collections.Generic.List
1[LANGUAGE] ToList[LANGUAGE](System.Collections.Generic.IEnumerable
1[LANGUAGE])' method, and this method cannot be translated into a store expression.
最佳答案
一个常见的错误,由于您可能会多次遇到它,请让我解释一下为什么会发生这种情况。
让我们阅读错误信息:
LINQ to Entities does not recognize the method
Linq to entities,将 linq 表达式转换为 SQL 的库(假设您使用的是 SQLServer 数据库),不理解您要求它执行的操作。它没有得到什么?
'System.Collections.Generic.List1[LANGUAGE] ToList[LANGUAGE] (System.Collections.Generic.IEnumerable1[LANGUAGE])' method
这是一个相当长且困惑的签名,因为我们不习惯像这样看到命名空间和返回类型,但它是您要求 Linq2Entities 翻译的方法:ToListEntityCollection<LANGUAGE>
上调用了扩展方法 .ToList()某处。
and this method cannot be translated into a store expression.
它说了,它无法将您的 Linq 表达式转换为存储(读取:SQL)表达式。
为什么 Linq2Entities 试图翻译您的 EntityCollection<LANGUAGE>.ToList()
到 SQL?因为 lambda 表达式(x => do some stuff
部分)中的所有内容都将被转换为 SQL。由于在显示的代码中没有任何地方提到 EntityCollectionCountryVM
中。的构造函数。
这就是 Zunair Zubair 的答案有效的原因:您的 .Select(),因此您的 lambda 表达式,不是由 Linq2Entities 翻译的,因为您是在一个对象上调用它,所以不涉及 SQL,因此没有翻译问题.
解决方案
很难给出任何建议,因为我不知道你想在构造函数中实现什么,但一个可能的解决方案是:
using (Context context = new Context() )
{
List<LANGUAGE> langs = context.LANGUAGE.ToList();
return context.COUNTRY.Select(c => new CountryVM(langs)
{
ID = c.ID,
DESCRIPTION = c.DESCRIPTION,
}).ToList();
}
并删除假设的 context.LANGUAGE.ToList();
来自第二个构造函数。这涉及对数据库的两个请求,可以进一步优化,但不能在不知道您的意图和表外键的情况下进行。
关于c# - 无法将 LINQ 查询结果转换为 ToList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23102593/