DbFunctions.TruncateTime LINQ equivalent in EF CORE

感情迁移 提交于 2019-12-01 02:56:54

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

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

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.

DbFunctions are not supported yet for EF Core. However you can use "Raw Sql Queries".

You can find documentation of "Raw Sql Queries" here

And also you can track here for DbFunctions for EF Core

I managed to rewrite this in Lambda as well and make it async. Seems to be working the same.

var temp = await _context.Events.Where(x => x.IsActive)
            .Include(a => a.Activity)
            .GroupBy(x => x.DateTimeFrom.Date)
            .Select(g => new { EventDate = g.Key, Events = g.ToList() }).ToDictionaryAsync(x => x.EventDate, x => x.Events);

EF Core 2.0 now supports mapping database functions to static methods on your context.

Check out the section 'Database scalar function mapping' here - https://docs.microsoft.com/en-us/ef/core/what-is-new/

To use DbFunctions in ASP.NET CORE You must create an object.

var DbF = Microsoft.EntityFrameworkCore.EF.Functions;

Now you can easily use it.

var now = DateTime.Now;

int count = db.Tbl.Count(w => DbF.DateDiffDay(now, w.RegisterDate) <= 3);

more detail on github

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!