我在我的asp.net应用程序中使用EF6
。在某些代码块中,我正在使用Transaction Scope
。以下是我的代码
using (VerbaTrackEntities dataContext = new VerbaTrackEntities())
{
TBL_TARGET target = dataContext.TBL_TARGET.Where(x => x.LNG_TARGET_ID == TargetID).SingleOrDefault();
if (target != null)
{
using (var trans = dataContext.Database.BeginTransaction())
{
try
{
System.Data.Entity.Core.Objects.ObjectContext oc = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)dataContext).ObjectContext;
foreach (var Targets in target.TBL_CASE_TARGET.ToList())
{
oc.DeleteObject(Targets);
}
foreach (var Targets in target.TBL_USER_TARGET.ToList())
{
oc.DeleteObject(Targets);
}
foreach (var Targets in target.TBL_FENCE_TARGET.ToList())
{
oc.DeleteObject(Targets);
}
foreach (var Targets in target.TBL_TARGET_COMM.ToList())
{
oc.DeleteObject(Targets);
}
foreach (var Targets in target.TBL_TRG_FENCE_STATUS.ToList())
{
oc.DeleteObject(Targets);
}
foreach (var Targets in target.TBL_TRG_MOVEMENT.ToList())
{
oc.DeleteObject(Targets);
}
TBL_IMAGE deleteImage = dataContext.TBL_IMAGE.Where(s => s.LNG_REF_ID == target.LNG_TARGET_ID && s.INT_TYPE_OF_IMAGE == 2).SingleOrDefault();
if (deleteImage != null)
oc.DeleteObject(deleteImage);
oc.SaveChanges();
dataContext.TBL_TARGET.Remove(target);
TargetEditForm.UpdateTargetSession(target, 1);
trans.Commit();
return dataContext.SaveChanges();
}
catch
{
trans.Rollback();
return 0;
}
}
}
}
trans.Commit();
失败时的以下代码。它进入catch
块以执行trans.Rollback
。这里抛出异常Underlying data cannot be rollback
。在调试时,我发现trans.Connection
是null
。什么是从这里回滚的正确方法..
答案 0 :(得分:3)
catch上的trans.Rollback不是必需的,因为事务在using
内。当调用事务中的Disposable()时,它会自动进行回滚。