【问题标题】:EFCore OrderBy not ordering correctly by date fieldEFCore OrderBy 未按日期字段正确排序
【发布时间】:2020-08-11 21:52:16
【问题描述】:

我有一个包含日期字段的数据库表中的 146 个项目的列表。在表中,它们没有特定的顺序,这要归功于 EF 无法(故意地,据我了解)保证批量插入的顺序。所以我正在使用以下内容提取所有内容:

// Records is a complex object consisting of a bunch of doubles, an integer ID, and a date
// Date is a DateTime, but with a time component of midnight.
var rawData = await Task.Run(() =>_context.Records.OrderBy(item => item.Date).ToList());

奇怪的是当我查看“自动”窗口时会发生什么。以下是最后 12 项的日期:

2020 年 7 月 31 日
2020 年 8 月 1 日
2020 年 8 月 2 日
2020 年 8 月 3 日
2020 年 8 月 4 日
2020 年 8 月 5 日
2020 年 8 月 6 日
2020 年 8 月 7 日
2020 年 8 月 8 日
2020 年 8 月 11 日
2020 年 8 月 10 日
2020 年 8 月 9 日

这……没有完全排序,尽管它我输入数据的顺序。

有趣的是,列表确实显示出被排序的迹象。该表(在 SQLite 中)使用标识列,以下是这 5 个项目的 ID,其顺序与它们在“自动”窗口中出现的顺序相同:

52
46
47
48
49
50
51
71
143
144
145
146

如您所见,由于缺乏更好的措辞,它看起来是半排序的。具体来说,我展示的前 9 个数据点(实际上是到那时为止的所有数据点)都已正确排序。然后我添加了一个数据点(8/11),重新请求数据,它看起来很好。然后我添加了下一个数据点(8/10),重新请求了数据,现在我添加的两个点都未排序。与下一个(8/9)相同。

前 143 个数据点与后三个数据点的区别在于,前三个数据点已经在 SQLite 文件中。添加最后三个是为了测试我的应用程序的添加/编辑功能,因此它们是在应用程序中创建的,并在我的调试会话期间写入文件。

我在这里不知所措。我在这里错过了什么吗?我的await 会不会搞砸了?还是我需要使用AsNoTracking 只是为了让我的数据以某种方式排序?

【问题讨论】:

  • SQLite 没有日期时间数据类型,很可能您使用的是文本。如果是转换成DateTime,可以在查询执行完后再进行排序。

标签: c# .net-core ef-core-3.1


【解决方案1】:

试试这个,

var rawData = await context.Records.OrderBy(item => item.Date).ToListAsync();

你的上下文是如何初始化的?

你可以试试

using (var context = serviceProvider.GetService<RecordsContext>())
{
  var rawData = await context.Records.OrderBy(item => item.Date).ToListAsync();
}

public class MyController
{
    private readonly RecordsContext _context;

    public MyController(RecordsContext context)
    {
      _context = context;
    }

    public async Task<List<Record>> GetRecords()
    {
      return await _context.Records.OrderBy(item => item.Date).ToListAsync();
    }
}

【讨论】:

  • 没有骰子。 ToListAsync() 没有修复它。不过谢谢! (根据您的第二个示例,我正在使用 DI 来获取我的上下文。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-29
  • 1970-01-01
相关资源
最近更新 更多