c# - .Net Core Connection 当前已登记事务
问题描述
我正在使用 .Net Core 2.1 编写集成测试我有一个看起来像这样的测试:
private TransactionScope scope;
[TestCleanup]
public void TestCleanup()
{
this.scope.Dispose();
}
[TestInitialize]
public void VerifyUsersHaveBeenSeeded()
{
var transactionOptions = new TransactionOptions {
IsolationLevel = IsolationLevel.ReadCommitted
};
//I've also tried using TransactionScopeOption.Required
this.scope = new TransactionScope(TransactionScopeOption.RequiresNew,
transactionOptions);
}
//Note I am using an MDF file during Testing.
protected AstootContext GetContext()
{
var optionsBuilder = new DbContextOptionsBuilder<AstootContext>();
optionsBuilder.UseSqlServer(this.ASTOOT_CONNECTION_STRING);
var context = new AstootContext(optionsBuilder.Options);
return context;
}
[TestMethod]
public async Task RestEzServiceVerifyUpdate()
{
var context = this.GetContext();
var expectedResult = context.Users.First();
var restEzService = GetDefaultService<User, UserDTO>(context);
var key = new object[] { expectedResult.Id };
var dto = await restEzService.Get(key);
var updatedName = "Updated";
dto.FirstName = updatedName;
var updatedDTO = await restEzService.Update(key, dto);
Assert.IsTrue(updatedDTO.FirstName == updatedName);
updatedDTO.Should().BeEquivalentTo(expectedResult,
o => o.Excluding(x => x.UniqueIdentifier).Excluding(x => x.FirstName));
context.Dispose();
}
更新方法调用:
var entity = await this._context.FindAsync(id).ConfigureAwait(false);
this.applyDTOToEntity(entity, dto);
await this._context.SaveChangesAsync().ConfigureAwait(false);
当它调用保存更改时,我得到一个错误:
System.InvalidOperationException:连接当前已登记事务。完成当前事务并重试。
我从上下文中调用的唯一地方是 1. 要在测试中获得预期结果,2. 获取更新的实体,3. 保存更改。
我将 transactionScopeOptions 设置为 Requires New,为什么会出现此错误?
解决方案
TransactionScopeOption.RequiresNew
尝试创建新事务。您确定,此时没有交易new TransactionScope
。
也许,您需要将其替换为TransactionScopeOption.Required
您还使用 async/await,因此添加到范围选项TransactionScopeAsyncFlowOption.Enabled
:
using (var scope = new TransactionScope(... ,
TransactionScopeAsyncFlowOption.Enabled))
推荐阅读
- pointers - 在没有通道的情况下同时计算斐波那契,但指针不起作用
- distributed - 为什么当消费者在 MassTransit RouterSlip 中抛出异常时不调用 Compensate 方法
- jquery - 我如何通过定价 00 美元的产品来查询 WooCommerce 产品?
- javascript - 如何通过 JavaScript 避免图像 src 字符串重复
- sql - 如何 PIVOT 查询中提到的选择结果
- git - git 不会在没有明确原因的情况下推送任何内容
- google-apps-script - 我可以在谷歌电子表格上的谷歌脚本上执行 getCursor() 吗?
- javascript - 如何从 JavaScript 中的表情符号中获取真正的字符代码?
- javascript - 如何获取地理位置数据并将其从浏览器发送到快递服务器
- android-studio - 向元素添加拖放功能