【问题标题】:Cached values returned after TransactionScope.Dispose()TransactionScope.Dispose() 后返回的缓存值
【发布时间】:2015-12-17 07:10:01
【问题描述】:

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

我在测试中使用 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();
    }

当我运行一个测试类时,一切正常。但是当我运行至少两个测试类时,我遇到了一个问题:在这个测试中(见下文)lasrQuestionId 等于数据库中的最后一个问题 id - 没关系,但是 actualResultId em> 等于 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() 有问题。我不知道哪里出了问题,你能解释一下我在这里做错了什么吗?提前致谢!

this.GetLastQuestion() 代码如下:

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

【问题讨论】:

    标签: c# entity-framework testing entity-framework-6 transactionscope


    【解决方案1】:

    这就是SQL Server引擎works

    对于具有特定种子/增量的给定身份属性,引擎不会重用身份值。如果特定的插入语句失败或插入语句回滚,则使用的标识值将丢失并且不会再次生成。这可能会导致生成后续标识值时出现间隙。

    【讨论】:

      猜你喜欢
      • 2017-07-27
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 2013-12-11
      • 2021-07-20
      • 1970-01-01
      • 2019-06-01
      • 1970-01-01
      相关资源
      最近更新 更多