获取实体框架中两个日期之间的天数

iso*_*son 6 entity-framework asp.net-core

我想按整数 + 从今天起经过的天数对行进行排序。

然而这个:

var now = DateTime.UtcNow;

db.Items.OrderBy(x => x.SomeInteger + (x.Date - now).Days);
Run Code Online (Sandbox Code Playgroud)

给出以下警告:

The LINQ expression 'orderby' could not be translated and will be evaluated locally.

在 .NET 框架中,可以这样做: DbFunctions.DiffDays

ASP.NET 核心中的等价物是什么?

Mik*_*ail 5

拉取请求使用

var lstPeople = cxt
.People.Where(p => EF.Functions.DateDiffDay(p.Birth, DateTime.Now) > 0 )
.ToList();
Run Code Online (Sandbox Code Playgroud)


iso*_*son 2

我已经在 github 上打开了这个问题,看起来它现在已经修复并且将在 2.1 中提供。

https://github.com/aspnet/EntityFrameworkCore/issues/10468

解决方法:

public static class DbUtility
{
    public static int DateDiff(string diffType, DateTime startDate, DateTime endDate)
    {
        throw new InvalidOperationException($"{nameof(DateDiff)} should be performed on database");
    }
}
Run Code Online (Sandbox Code Playgroud)

ApplicationDbContext

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.HasDbFunction(typeof(DbUtility)
        .GetMethod(nameof(DbUtility.DateDiff)))
        .HasTranslation(args => {
            var newArgs = args.ToArray();
            newArgs[0] = new SqlFragmentExpression((string)((ConstantExpression)newArgs[0]).Value);
            return new SqlFunctionExpression(
                "DATEDIFF",
                typeof(int),
                newArgs);
        });
}
Run Code Online (Sandbox Code Playgroud)

像这样使用:

DbUtility.DateDiff("day", x.DateAdded, now)
Run Code Online (Sandbox Code Playgroud)