我一直在尝试使用字符串列表对LINQ查询进行排序。我正在查询学生条款,包括TermCourses。 该代码引发以下错误:
System.NotSupportedException:'LINQ to Entities无法识别方法'Int32 IndexOf(System.String)'方法,并且该方法无法转换为商店表达式。'
我已经使用DataTables
进行了这种排序,其中我只有行,但是没有在EF和对象树中。
如何解决此问题?
这是我的代码:
private static readonly List<string> SortingOrder =
new List<string>()
{
"Fall",
"Spring",
"Summer"
};
using (var context = new EUContext())
{
var tmp = context.Terms.Include(x=>x.TermCourses)
.OrderBy(x => x.AcademicYear)
.ThenBy(x => SortingOrder.IndexOf(x.TermRegistered))
.Where(x => x.StudentID == studentId && x.DepartmentID == departmentId);
return tmp.ToList();
}
答案 0 :(得分:2)
您试图通过仅在代码/ RAM中可用的方法对数据库进行排序。您需要将排序控制权转移回本地计算机:
private static readonly List<string> SortingOrder =
new List<string>()
{
{ "Fall" },
{ "Spring" },
{ "Summer" }
};
using (var context = new EUContext())
{
// this part will query the database
var tmp = context.Terms
.Include(x=>x.TermCourses)
.Where(x => x.StudentID == studentId && x.DepartmentID == departmentId)
// this will transfer controll to your local machine
.AsEnumerable()
// sort on your local machine by the data you have in your RAM
.OrderBy(x => x.AcademicYear)
.ThenBy(x => SortingOrder.IndexOf(x.TermRegistered));
return tmp.ToList();
}