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?
Finally, in my unit test I made sure to clear the event log just before the assert part of my test to ensure I don't get a false positive due to events that were logged during the arrange part of my test:
If using the InMemory provider you get just one event: I hadn't expected the events logged to change depending on the DB provider. To anyone wanting to look into this more, I captured the event details by changing Ilya's logging code as follows:
InMemory is not intended to be a relational database. In my case i get exactly the same error when unittesting a WCF-service with InMemory. The test that goes wrong asks for the databaseName "dbContext.Database.GetDbConnection ().Database".
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); }
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.UseInMemoryDatabase("TestDb"); options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With