我想从今天开始整数+天数订购行。
不过这个:
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核心中的等价物是什么?
我已经在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)