下面的代码在一个循环中执行了很多次。当我执行以下代码时,它偶尔会生成一个外键异常,这很好,因为它已被处理并且我尝试对事务进行角色回复。但是,在下一次运行时,它会生成相同的异常,并且会一遍又一遍地这样做,即使数据是正确的。
我们有一个存储上下文的单例类:
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!
}