我是一个新手,最近开始使用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);
我的目标是删除所有过期的书籍(它们的时间戳已过我想要跟踪它们的时间)。
因此,我得到了异常:
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.
经过一番调查,我发现这是因为EF无法将我的DateTime比较解析到SQL查询中,因此我尝试使用https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.sqlserverdbfunctionsextensions.datediffhour?view=efcore-5.0#Microsoft_EntityFrameworkCore_SqlServerDbFunctionsExtensions_DateDiffHour_Microsoft_EntityFrameworkCore_DbFunctions_System_DateTime_System_DateTime中的DbFunctions.DateDiffHour()方法。
问题在于,即使我已安装并导入了Nuget EF Core 5,我仍无法访问任何DbFunctions方法:
同样适用于EF.Functions(没有公共方法):![在此输入图片描述](https://istack.dev59.com/RDxar.webp)
using Microsoft.EntityFrameworkCore;
。 - DavidGMicrosoft.EntityFrameworkCore.SqlServer
包。 - Svyatoslav DanylivMicrosoft.EntityFrameworkCore.SqlServer
包? - DavidG