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

70

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

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

    // some other stuff

    transaction.Commit();
}

然而,测试运行器显示以下错误:

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.

我该如何解决这个错误?

2个回答

143
在声明内存数据库的代码中,通过以下方式将上下文配置为忽略该错误:
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); 
}

2
你救了我的一天,我的ResilientTransaction在单元测试中失败了。添加这个已经修复了所有问题。非常感谢。 - Pankaj Parkar

14

我使用了来自 @tomRedox 的答案,但对其进行了修改,以在 ASP.NET Core 2.0 startup.cs 文件中使用。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接