问题描述
我正在开发一个系统,该系统基本上将数据从一组表迁移到另一组表。一切正常,但是我决定采用事务,而不是仅仅对部分完成的事情失败。 (也就是说,如果发生某些异常,我想回滚而不是迁移部分数据。)
我有一个服务(采用3层架构方式,而不是Web),该服务在数据访问层上开始事务。数据上下文在包含许多方法的数据访问类中共享。这些方法使用各种LINQ-to-sql技术来更新/插入/删除。所有LINQ-to-sql“选择”都在CompiledQueries中。
\“ BeginTransaction \”方法启动如下事务:
Public Sub BeginTransaction() Implements ITransactionalQueriesBase.BeginTransaction
Me.Context.Connection.open()
Me.Context.Transaction = Context.Connection.BeginTransaction()
IsInTransaction = True
End Sub
基本上,我编写了一个测试,该测试将启动一个事务,将其插入表中,然后尝试在事务期间全部检索刚刚插入的值。我这样做是因为我想断言insert方法实际上是在尝试插入。然后,在测试期间,我将回滚,然后进行测试以确保新插入的值未真正提交给表。测试看起来像这样:
<TestMethod()>
Public Sub FacilityService_Can_Rollback_A_Transaction()
faciService.BeginTransaction()
Dim devApp = UnitTestHelper.CreateDevelopmentApplication(devService.GetDevelopmentType(\"NEWFACI\").ID,1,1)
Dim devInsertRes = devService.InsertDevelopmentApplication(devApp)
Assert.IsTrue(devInsertRes.ReturnValue > 0)
For Each dir1 In devInsertRes.Messages
Assert.Fail(dir1)
Next
Dim migrationResult = faciService.ProcessNewFacilityDevelopment(devInsertRes.ReturnValue)
Assert.IsTrue(migrationResult.ReturnValue.InsertResult)
Dim faciRetrieval1 = faciService.GetFacilityByID(migrationResult.ReturnValue.FacilityID)
Assert.IsNotNull(faciRetrieval1.ReturnValue)
faciService.Rollback()
Dim faciRetrieval2 = faciService.GetFacilityByID(migrationResult.ReturnValue.FacilityID)
Assert.IsNull(faciRetrieval2.ReturnValue)
End Sub
所以,对我的问题...
当测试进入“ faciRetrieval1”步骤时,它将在此停留约30-60秒,然后继续进行。我不确定为什么会这样。如果我在SSMS的事务中运行相同的查询,则会立即发生。有人有什么想法吗?该数据库是sql Server 2008 SP1(R2?)。
解决方法
我发现,如果您有一个使用事务的数据上下文,则其他任何数据上下文似乎都无法从相同类型的另一个上下文中进行选择。
我最终通过在发生事务的每个选择/更新/删除过程中使用相同的上下文来修复它。