获取Entity Framework中两个日期之间的天数

问题描述 投票:2回答:1

我想从今天开始整数+天数订购行。

不过这个:

var now = DateTime.UtcNow;

db.Items.OrderBy(x => x.SomeInteger + (x.Date - now).Days);

给出以下警告:

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

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

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

entity-framework asp.net-core
1个回答
1
投票

我已经在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");
    }
}

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

像这样使用:

DbUtility.DateDiff("day", x.DateAdded, now)
© www.soinside.com 2019 - 2024. All rights reserved.