How to suppress InMemoryEventId.TransactionIgnoredWarning when unit testing with in-memory database with transactions? c# entity-framework-core in-memory-database


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())
        result = await _context.SaveChangesAsync();

        // some other stuff


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 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?

9/30/2019 9:04:01 AM

Accepted Answer

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>()
            // don't raise the error warning us that the in memory db doesn't support transactions
            .ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))

        return new MyDbContext(options); 
6/18/2019 11:17:13 AM

Popular Answer

I used the answer from @tomRedox but varied it for use in an ASP.NET Core 2.0 startup.cs file.

services.AddDbContext<MyDbContext>(options =>
                options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow