Search code examples
c#asp.net-coreentity-framework-corein-memory-database

How to suppress InMemoryEventId.TransactionIgnoredWarning when unit testing with in-memory database with transactions?


I'm using an EF Core in-memory database and I'm trying to run a unit test on a method that uses transactions:

using (var transaction = await _context.Database.BeginTransactionAsync())
{
    _context.Update(item);
    result = await _context.SaveChangesAsync();

    // some other stuff

    transaction.Commit();
}

However, I'm getting this error from the test runner:

System.InvalidOperationException: Warning as error exception for warning 'InMemoryEventId.TransactionIgnoredWarning': Transactions are not supported by the in-memory store. See http://go.microsoft.com/fwlink/?LinkId=800142 To suppress this Exception use the DbContextOptionsBuilder.ConfigureWarnings API. ConfigureWarnings can be used when overriding the DbContext.OnConfiguring method or using AddDbContext on the application service provider.

How do I suppress that error?


Solution

  • In the code where you declare the in-memory database, configure the context to ignore that error as follows:

    public MyDbContext GetContextWithInMemoryDb()
    {
        var options = new DbContextOptionsBuilder<MyDbContext>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            // don't raise the error warning us that the in memory db doesn't support transactions
            .ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
            .Options;
    
        return new MyDbContext(options); 
    }