tom*_*dox 18 c# in-memory-database entity-framework-core asp.net-core
我正在使用EF Core内存数据库,我正在尝试对使用事务的方法运行单元测试:
using (var transaction = await _context.Database.BeginTransactionAsync())
{
_context.Update(item);
result = await _context.SaveChangesAsync();
// some other stuff
transaction.Commit();
}
Run Code Online (Sandbox Code Playgroud)
但是,我从测试运行器中收到此错误:
System.InvalidOperationException:警告为"InMemoryEventId.TransactionIgnoredWarning"的错误异常:内存存储不支持事务.请参阅 http://go.microsoft.com/fwlink/?LinkId=800142要禁止此异常,请使用DbContextOptionsBuilder.ConfigureWarnings API.重写DbContext.OnConfiguring方法或在应用程序服务提供程序上使用AddDbContext时,可以使用ConfigureWarnings.
如何抑制该错误?
tom*_*dox 46
在声明内存数据库的代码中,配置上下文以忽略该错误,如下所示:
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);
}
Run Code Online (Sandbox Code Playgroud)
Cri*_*inH 10
我使用了来自 @tomRedox 的答案,但在 ASP.NET Core 2.0 startup.cs文件中使用了它。
services.AddDbContext<MyDbContext>(options =>
{
options.UseInMemoryDatabase("TestDb");
options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3526 次 |
| 最近记录: |