Compare date with today on the server side with EntityFramework Core and linq to entities entity-framework-core


I'm trying to translate some code from EF6 to EF Core 1 RC1 and I'm stuck at the point on wich I need to compare the dates with the current one, on the server side using linq. There is also another part of the query wich was getting the day of week of these dates. The EF6 code uses the SqlFunctions class wich is fully qualified as System.Data.Entity.SqlServer.SqlFunctions, that afaik hasn't been ported to the new version. What's the recommended approach or the alternative to keep this working on EF Core?

The original linq to entities query is like this:

var result = db.Logs.Select(log => new {
      Date = log.Date,
      Rel = System.Data.Entity.SqlServer.SqlFunctions.DateDiff("day", log.Date, System.Data.Entity.SqlServer.SqlFunctions.GetDate()),
      Dow = System.Data.Entity.SqlServer.SqlFunctions.DatePart("dw", log.Date) - 1 
4/11/2016 4:06:56 PM

Accepted Answer

For the moment, Sql Functions are not supported, here is the opened issue

Provide standard LINQ methods that correspond to standard SQL operations (something like DbFunctions from EF6)

Here are some alternatives you can try:

5/23/2017 11:46:36 AM

Popular Answer

It is possible to make use of the datepart SQL function by wrapping it with the DbFunctionAttribute. Same is possible for datediff and so on. Tricky part is to tell ef core not to handle the datepart type parameter as a string. Example:


public int? DatePart(string datePartArg, DateTime? date) => throw new Exception();

public void OnModelCreating(DbModelBuilder modelBuilder) {
    var methodInfo = typeof(DbContext).GetRuntimeMethod(nameof(DatePart), new[] { typeof(string), typeof(DateTime) });
        .HasTranslation(args => new SqlFunctionExpression(nameof(DatePart), typeof(int?), new[]
                        new SqlFragmentExpression(args.ToArray()[0].ToString()),


repository.GroupBy(x => dbContext.DatePart("week", x.CreatedAt));

some more info:

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow