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

时间:2017-09-07 22:23:00

标签: entity-framework asp.net-core

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

但是这个:

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核心中的等价物是什么?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

pull request使用

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