0
以下代碼位於執行多次的循環中。當我執行下面的代碼時,它偶爾會生成一個外鍵異常,這是很好的,因爲它被處理了,我試圖將事務作用回去。但是,在下一次運行時,即使數據正確,它也會一次又一次地生成相同的異常。實體框架事務不回滾
我們有存儲上下文中的單例類:
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();
}
這是更新()方法,它使異常
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!
}