EF Core 7.0 中使用下面的 LINQ :
await DbSet.ById(userId).ExecuteUpdateAsync(u =>
u.SetProperty(x => x.LastLogin, x => DateTime.Now));
在运行时报错:
Error Message:
System.InvalidOperationException : The LINQ expression 'DbSet<User>()
.Where(u => ((IEntity<Guid>)u).Id.Equals((object)__id_0))
.ExecuteUpdate(u => u.SetProperty<DateTime?>(
propertyExpression: x => x.LastLogin,
valueExpression: x => (DateTime?)DateTime.Now))' 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.
Stack Trace:
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
请问如何解决?
改成类似这样呢
await DbSet.Where(u => u.Id == userId)
.SetProperty(u => u.LastLogin, DateTime.Now)
.UpdateAsync();
SetProperty 不支持 IQueryable,ExecuteUpdateAsync 是 EF Core 7 引入的新特性,详见 ExecuteUpdate and ExecuteDelete (Bulk updates)
是 EF Core In-Memory Database 的问题,用 SQL Server 时没这个问题