.Net Core Connection当前已登记事务

时间:2018-06-21 03:13:34

标签: c# entity-framework transactions .net-core mstest

我正在使用.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,为什么会出现此错误?

1 个答案:

答案 0 :(得分:7)

TransactionScopeOption.RequiresNew尝试创建新交易。您确定在new TransactionScope点没有事务。

也许您需要将其替换为TransactionScopeOption.Required

还使用async / await,因此将添加到范围选项TransactionScopeAsyncFlowOption.Enabled

using (var scope = new TransactionScope(... ,
  TransactionScopeAsyncFlowOption.Enabled))