如何在使用内存数据库进行单元测试时抑制 InMemoryEventId.TransactionIgnoredWarning?

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

我使用的是 EF Core 内存数据库,我正在尝试 运行 对使用事务的方法进行单元测试:

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

    // some other stuff

    transaction.Commit();
}

但是,我在测试中遇到了这个错误 运行ner:

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.

如何抑制该错误?

在声明内存数据库的代码中,配置上下文以忽略该错误,如下所示:

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); 
}

我使用了@tomRedox 的答案,但为了在 ASP.NET Core 2.0 startup.cs 文件中使用而改变了它。

services.AddDbContext<MyDbContext>(options =>
{
    options.UseInMemoryDatabase("TestDb");
    options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
});