在服务器端使用 EntityFramework Core 和 linq to entities 比较日期和今天

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

我正在尝试将一些代码从 EF6 转换为 EF Core 1 RC1,但我卡在需要在服务器端使用 linq 将日期与当前日期进行比较的地步。查询的另一部分是获取这些日期的星期几。

EF6 代码使用完全符合 System.Data.Entity.SqlServer.SqlFunctions 的 SqlFunctions class,afaik 尚未移植到新版本。

在 EF Core 上保持此功能的推荐方法或替代方法是什么?

原来的linq to entities查询是这样的:

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 
});

暂时Sql功能不支持,这里是打开的issue

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

您可以尝试以下替代方法:

可以通过使用 DbFunctionAttribute 包装来使用 datepart SQL 函数。 datediff 等也是可能的。 棘手的部分是告诉 ef 核心不要将 datepart 类型参数作为字符串处理。示例:

数据库上下文:

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) });
    modelBuilder
        .HasDbFunction(methodInfo)
        .HasTranslation(args => new SqlFunctionExpression(nameof(DatePart), typeof(int?), new[]
                {
                        new SqlFragmentExpression(args.ToArray()[0].ToString()),
                        args.ToArray()[1]
                }));
}

查询:

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

更多信息:https://github.com/aspnet/EntityFrameworkCore/issues/10404