ExecuteDeleteAsync throws error on inmemory db

520 Views Asked by At

I was implementing the latest ef core 7 features ExecuteDeleteAsync(). Since that my test is failing. But is working on a real MsSql Server. I'm using an inmemory db and I am not sure if this is not working because of this statement:

However, it is sometimes useful to execute update or delete commands on the database without involving the change tracker. EF7 enables this with the new ExecuteUpdate and ExecuteDelete methods. These methods are applied to a LINQ query and will update or delete entities in the database based on the results of that query.

In Memory DB is Microsoft.EntityFrameworkCore.InMemory and in it's latest version.

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

Here is my db context:

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

        builder.UseInMemoryDatabase(dbName);

        return new DashboardDbContext(builder.Options);
    }

Exception:

{"The LINQ expression 'DbSet()\r\n
.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 for more information."}

1

There are 1 best solutions below

1
nvoigt On

Assuming ModifiedTime is a DateTime field in your model and correctly represents your database and dateToKeepData is a local DateTime variable in your code, it should work.

But please note that you should not use the InMemory Database for your unit tests. Quoting Microsoft themselves:

While some users use the in-memory database for testing, this is discouraged.

You can use other in memory databases, like SQLite. That should work. I'm doing exaxtly that in my code and with SQLite it works fine. Maybe time to heed Microsofts warning and switch to a proper in memory database, not just Microsofts mock version of one.