“无法翻译 LINQ 表达式”与 LINQ 查询中的 DateTime 比较?

K. *_* Vu 7 c# entity-framework entity-framework-5 entity-framework-core

我是一名新手,最近刚刚开始在项目中使用 EF Core 5,并且遇到以下查询问题:

TimeSpan bookTimeToLive = TimeSpan.FromHours(10);
IList<Book>? expiredBooks = dbContext.Value.Books.AsQueryable()
                    .Where(x => DateTime.UtcNow - x.UtcTimeStamp > bookTimeToLive)
                    .ToList();

// Get list of expired Books to remove them
dbContext.Value.RemoveRange(expiredBooks);
await dbContext.Value.SaveChangesAsync(cancellationToken);

Run Code Online (Sandbox Code Playgroud)

我的目标是删除所有过期的书籍(它们的时间戳超过了我想要跟踪它们的时间)。

这样,我得到了例外:

The LINQ expression 'DbSet<Books>()
    .Where(d => DateTime.UtcNow - d.UtcTimeStamp > __bookTimeToLive_0)' could not be translated. Either
 rewrite the query in a form that can be translated, or switch to client evaluation explicitly by 
inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See 
https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
Run Code Online (Sandbox Code Playgroud)

经过一番挖掘,我意识到这是因为 EF 无法将我的 DateTime 比较解析为 SQL 查询,因此我尝试使用https://learn.microsoft.com/en-us/中的 DbFunctions.DateDiffHour() 方法dotnet/api/microsoft.entityframeworkcore.sqlserverdbfunctionsextensions.datediffhour?view=efcore-5.0#Microsoft_EntityFrameworkCore_SqlServerDbFunctionsExtensions_DateDiffHour_Microsoft_EntityFrameworkCore_DbFunctions_System_DateTime_System_DateTime _

现在的问题是,即使我在类中安装并导入了 Nuget EF Core 5,我也无法访问任何 DbFunctions 方法:

在此输入图像描述

这同样适用于 EF.Functions(无公共方法): 在此输入图像描述

这可能是一个错误还是我没有正确使用这些类?这是实现我想要实现的目标的正确方法吗?干杯!

Ste*_* Py 10

如果时间分量是静态的(所有行都相同),那么一个简单的选择是将其应用于当前日期以形成一个截止值以进行比较:

代替:

TimeSpan bookTimeToLive = TimeSpan.FromHours(10);
IList<Book> expiredBooks = dbContext.Value.Books
                .Where(x => DateTime.UtcNow - x.UtcTimeStamp > bookTimeToLive)
                .ToList();
Run Code Online (Sandbox Code Playgroud)

像这样的东西。不需要 DbFunctions。

DateTime expiryCutoff = DateTime.UtcNow.AddHours(-10);
Ilist<Book> expiredBooks = dbContext.Books
    .Where(x => x.UtTimeStamp < expiryCutoff)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

如果它是动态的,DateTime类似的方法AddHours仍然会翻译:

Ilist<Book> expiredBooks = dbContext.Books
    .Where(x => x.UtTimeStamp.AddHours(x.ExpiryCutoff) < DateTime.UtcNow)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

其中 ExpiryCutoff 是记录中的数据驱动值。(或相关表达)