c# - 为什么 EF 无法按另一个集合的顺序对项目进行排序以及如何解决?

标签 c# linq sorting entity-framework-6

我一直在尝试使用字符串列表对 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/

相关文章:

c# - NEST 2.0不会将某些字段保留到ElasticSearch 2.0中

c# - 如何在我的项目中重用 xaml 命名空间定义

c# - UWP - XDocument 等效于 XMLNodeList

c# - LINQ to Entities Include() 不起作用

python - 对数字和数组的列表进行排序?

C# Xml SelectSingleNode 返回 null

c# - 选择 Tag Helper 获取值和文本

c# - 使用 DropDownList 填充 Gridview

python - 手动排序 4 个数字

java - 如何对 SWT 列进行降序排序