ExecuteDeleteAsync 在内存数据库上引发错误[重复]

问题描述 投票:0回答:1

我正在实现最新的 ef core 7 功能 ExecuteDeleteAsync()。从那以后我的测试失败了。但正在开发一个真正的 MsSql 服务器。我正在使用 内存数据库,我不确定这是否因为这个语句而不起作用:

但是,有时在不涉及更改跟踪器的情况下对数据库执行更新或删除命令很有用。 EF7 通过新的 ExecuteUpdate 和 ExecuteDelete 方法实现了这一点。这些方法应用于 LINQ 查询,并将根据该查询的结果更新或删除数据库中的实体。

内存数据库是 Microsoft.EntityFrameworkCore.InMemory 并且是最新版本。

public async Task<int> DeleteWhere(Expression<Func<T, bool>> predicate)
{
  var amount = await _dbSet.Where(predicate).ExecuteDeleteAsync();
  return amount;
}

这是我的数据库上下文:

 public DashboardDbContext CreateDashboardContext()
    {
        var dbName = $"xUnitTest{_instanceCount++}";
        var builder = new DbContextOptionsBuilder<DashboardDbContext>();

        builder.UseInMemoryDatabase(dbName);

        return new DashboardDbContext(builder.Options);
    }

例外:

{“LINQ 表达式 'DbSet()
.Where(b => b.ModifiedTime < __dateToKeepData_0)\r\n .ExecuteDelete()' 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 了解更多信息。"}

c# entity-framework .net-6.0 in-memory-database ef-core-7.0
1个回答
0
投票

假设

ModifiedTime
是模型中的 DateTime 字段并正确表示您的数据库,并且
dateToKeepData
是代码中的本地 DateTime 变量,那么它 应该 可以工作。

但请注意,您不应该使用 InMemory 数据库进行单元测试。引用微软自己的话:

虽然有些用户使用内存数据库进行测试,但不鼓励这样做。

您可以使用其他内存数据库,例如 SQLite。那应该有效。我在我的代码中确实做到了这一点,并且使用 SQLite 它工作得很好。也许是时候注意微软的警告并切换到正确的内存数据库,而不仅仅是微软的模拟版本。

© www.soinside.com 2019 - 2024. All rights reserved.