TransactionScope.Dispose() 后返回的缓存值

Cached values returned after TransactionScope.Dispose()

我是集成测试的新手,我正在寻找有关解决我的问题的一些解释和建议:

我在测试中使用 TransactionScope 来保持数据库清洁并在每次测试前创建新的 TransactionScope 并在每次测试后处理它:

 [SetUp]
    public void Init()
    {
        this.scope = new TransactionScope(
            TransactionScopeOption.Required,
            new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted },
            TransactionScopeAsyncFlowOption.Enabled);
        this.context = new SportsPerformanceDbContext();
        this.questRepo = new QuestionRepository(this.context);
    }

    [TearDown]
    public void CleanAll()
    {
        this.context.Dispose();
        this.scope.Dispose();
    }

当我 运行 一次测试 class 时一切正常。但是当我 运行 至少两次测试 classes 时,我遇到了一个问题:在这个测试中(见下文) lasrQuestionId 等于来自数据库 - 没关系,但是 actualResultId 等于 Id_of_the_last_added_question_in_tests_with_transaction_scope + 1:

[Test]
    public async void AddAsyncTest()
    {
        // Arrange
        var questionModel = new QuestionModel
        {
            //some properties
        };
        Question lastQuestion = this.GetLastQuestion();
        var lastQuestionId = lastQuestion?.Id ?? 0;

        // Act
        var addResult = await this.questRepo.AddAsync(questionModel);
        var actualResult = addResult.Value;

        // Assert
        Assert.AreEqual(lastQuestionId + 1, actualResult.Id);
        // some other assertions
    }

所以我有以下内容,例如,lastQuestionId 是 5(数据库中有 5 个问题),但是 actualResult Id 是 16(因为我之前在其他测试中添加了一些问题)...我假设我的 contextscope.dispose()[=32 有问题=].我不知道哪里出了问题,你能解释一下我在这里做错了什么吗?提前致谢!

this.GetLastQuestion()代码如下:

 private Question GetLastQuestion()
    {
        using (var ctx = new SportsPerformanceDbContext())
        {
            return ctx.Question
             .OrderByDescending(q => q.Id)
             .FirstOrDefault();
        }
    }

这就是 SQL 服务器引擎 works:

For a given identity property with specific seed/increment, the identity values are not reused by the engine. If a particular insert statement fails or if the insert statement is rolled back then the consumed identity values are lost and will not be generated again. This can result in gaps when the subsequent identity values are generated.