我一直在尝试使用字符串列表对 LINQ 查询进行排序。我正在查询学生学期并包括学期类(class)。 代码抛出以下错误:
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Int32 IndexOf(System.String)' method, and this method cannot be translated into a store expression.'
我已经使用 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();
}
最佳答案
您正在尝试通过仅在您的代码/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();
}
关于c# - 为什么 EF 无法按另一个集合的顺序对项目进行排序以及如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53480621/