EF CORE 中的 DbFunctions.TruncateTime LINQ 等效项

2022-01-04 00:00:00 sqlite entity-framework-core linq

我的 .net 应用程序中有以下功能 LINQ

I have the following functioning LINQ in my .net app

    public ActionResult Index()
    {
        Dictionary<DateTime?, List<Event>> result;
        result = (from events in db.Events.Include("Activity")
                      where events.IsActive
                      group events by DbFunctions.TruncateTime(events.DateTimeFrom) into dateGroup
                      select new { EventDate = dateGroup.Key, Events = dateGroup.ToList() }).ToDictionary(x => x.EventDate, x => x.Events);

        return View(result);
    }

当我在 EF Core 中使用它时,我无法使用 DbFunctions.我如何重写它以使其在 Microsoft.EntityFrameworkCore 中工作?如果这有所作为,我正在使用 SQLite.

When I use this in EF Core, I can't use DbFunctions. How can I rewrite this to make it work in Microsoft.EntityFrameworkCore ? I am using SQLite if that makes a difference.

推荐答案

在 EF6 中使用 DbFunctions.TruncateTime 代替 DateTime.Date 属性,因为某些原因后者不支持.

In EF6 DbFunctions.TruncateTime is used instead of DateTime.Date property because for some reason the later is not supported.

在 EF Core 中不需要前者,因为 DateTime.Date 现在可以正确识别和翻译.

In EF Core the former is not needed simply because DateTime.Date now is recognized and translated correctly.

group events by events.DateTimeFrom.Date into dateGroup

不幸的是,目前还没有支持什么的文档,所以作为一般的经验法则,总是尝试相应的 CLR 方法/属性(如果有)并检查它是否转换为 SQL 以及如何转换.

Unfortunately there is no documentation (yet) of what is supported, so as a general rule of thumb, always try the corresponding CLR method/property (if any) and check if it translates to SQL and how.

相关文章