[英]Entity Framework Transaction not rolling back
以下代碼處於循環中,該循環執行多次。 當我執行以下代碼時,它偶爾會生成一個外鍵異常,這很好,因為它已得到處理,並且我嘗試回溯事務。 但是,在下一次運行時,即使數據正確,它也會生成相同的異常,並一遍又一遍地執行。
我們有一個單例類來存儲上下文:
public class MyDatabaseContext
{
private static MyDatabaseContext _instance;
public static MyDatabaseContext_Instance
{
get
{
if (_instance == null)
{
_instance = new MyDatabaseContext();
}
return _instance;
}
}
public MyEntities Context;
private MyDatabaseContext()
{
Context = new MyEntities();
}
}
}
減少循環主要部分的版本:
MyEntities entities = MyDatabaseContext.Instance.Context;
// Begin new transaction
entities.Connection.Open();
DbTransaction transaction = entities.Connection.BeginTransaction();
try {
// Inside the update, we modify some data and call saveChanges() on the same
// database context, see below
dataObject.Update()
// do more stuff to data here
if (dataObject.isValid())
{
transaction.Commit();
}
} catch (Exception ex) {
// Rollback transaction
transaction.Rollback();
} fincally {
entities.Connection.Close();
}
這是Update()方法,它會導致異常
public static Update() {
// get same database context
MyEntities entities = MyDatabaseContext.Instance.Context;
// Update data, wont show here, but a foreign key is set to 0 which
//will cause an exception
entities.saveChanges() // Exception thrown here!
}
MS SQL不支持嵌套事務。 很可能您已經在事務中,因此開始/提交/回滾是邏輯事務,而不是物理數據庫事務。
嘗試使用SQL事件探查器對其進行檢查,以查看實際發生的情況。
簡單(但不是最好的解決方案)的解決方案是,無論Rollback
執行Rollback
,實際上都需要關閉連接並重新開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.