EFCore OrderBy无法按日期字段正确排序

时间:2020-08-11 21:52:16

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

我在具有日期字段的数据库表中有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来使我的数据以某种方式排序?

1 个答案:

答案 0 :(得分:-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();
    }
}