Database.BeginTransaction()实体框架回滚抛出异常

时间:2015-06-11 11:57:48

标签: c# asp.net entity-framework transactionscope

我在我的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.Connectionnull。什么是从这里回滚的正确方法..

1 个答案:

答案 0 :(得分:3)

catch上的trans.Rollback不是必需的,因为事务在using内。当调用事务中的Disposable()时,它会自动进行回滚。