Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare date with today on the server side with EntityFramework Core and linq to entities

I'm trying to translate some code from EF6 to EF Core 1 RC1 and I'm stuck at the point on which I need to compare the dates with the current one, on the server side using linq. There is also another part of the query which was getting the day of week of these dates.

The EF6 code uses the SqlFunctions class which 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 
});
like image 769
Vi100 Avatar asked Apr 11 '16 16:04

Vi100


1 Answers

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:

  • You can try using raw sql using context.set().FromSql("...").
  • Otherwise you can create computed colums on the db side and mark these columns as generated in the EF model
like image 164
Thomas Avatar answered Nov 13 '22 06:11

Thomas