我首先使用 EF 代码,但我似乎无法让我的查询在 TransactionScope 的上下文中运行。我已经看到了几十个这样做的例子,但是我的插入没有被事务处理;此测试失败,记录仍在数据库中,但未引发错误。
我在 SQL 2008 上,并且 MSDTC 已打开,但我的理解是它不需要,因为在此环境中不应将其升级为分布式事务。无论如何,我认为如果它尝试升级但失败了,我会得到一个例外。
<TestMethod()>
Public Sub CanEnrollInTransaction()
Dim id = Guid.NewGuid().ToString()
Using foo = New TransactionScope(
TransactionScopeOption.Required,
New TransactionOptions() With {.IsolationLevel = IsolationLevel.Serializable})
Dim context = New WebPersistentDataContext() 'Subclass of DbContext
context.WebsiteErrors.Add(New WebsiteError() With {
.WebsiteId = 21,
.AdditionalInformation = id,
.BrowserInformation = "Unit test",
.ErrorDateTime = DateTime.Now,
.ErrorMessage = "Unit Test"})
'No transaction in SQL Profiler
context.SaveChanges()
'Tried this too...
'Dim objectContext = CType(context, IObjectContextAdapter).ObjectContext
'objectContext.SaveChanges()
'Not committing should roll back the transaction when scope is disposed
End Using
Dim newContext = New WebPersistentDataContext()
If newContext.WebsiteErrors.Any(Function(e) e.AdditionalInformation = id) Then
Assert.Fail("record is still there, transaction did not roll back")
End If
End Sub
谁能解释我在这里做错了什么?为什么没有事务,更不用说回滚了?
更新 - 上下文类:
Public Class WebPersistentDataContext
Inherits DbContext
Public Property WebsiteErrors As DbSet(Of WebsiteError)
Public Property Websites As DbSet(Of Website)
Public Property WebSettings As DbSet(Of WebSetting)
Public Sub New()
End Sub
End Class