c# - .Net Core Connection 目前有事务登记

标签 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: Connection currently has transaction enlisted. Finish current transaction and retry.



我从上下文中调用的唯一地方是 1. 要在测试中获得预期结果,2. 获取更新的实体,3. 保存更改。

我已将 transactionScopeOptions 设置为 Requires New,为什么会出现此错误?

最佳答案

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

也许,您需要将其替换为 TransactionScopeOption.Required
你也使用 async/await,所以添加到范围选项 TransactionScopeAsyncFlowOption.Enabled :

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

关于c# - .Net Core Connection 目前有事务登记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50959848/

相关文章:

javascript - 将 webSQL 结果存储到 var 以供其他函数使用?

java - JOOQ如何启动事务和回滚?

c# - TreeViewItem 无法在 BackgroundWorker 中更新

c# - C++ 库适用于 vb6 但不适用于 c#

c# - 如何在代码隐藏中将 ItemsPanelTemplate 设置为动态创建的网格

c# - 如何创建可重用的 Entity Framework 投影表达式?

c# - ASP.NET 为 ActionResult 提供参数

c# - 指定主键等信息是否会影响 EntityFramework 性能?

c# - 使用 Entity Framework 动态选择表

java - 命令模式应用的真实世界示例