/// <summary> /// 将方法调用打包,使只用一个数据连接 /// 同CRLDbConnectionScope /// </summary> /// <param name="action"></param> public void PackageMethod(Action action) { using (var context = new CRLDbConnectionScope()) { try { action(); } catch (Exception ero) { context.Dispose(); throw ero; } } }
/// <summary> /// 使用DbTransaction封装事务,不能跨库 /// 请将数据访问对象写在方法体内 /// 可嵌套调用 /// </summary> /// <param name="method"></param> /// <param name="error"></param> /// <returns></returns> public bool PackageTrans2(TransMethod method, out string error) { error = ""; var _useCRLContext = CallContext.GetData <bool>(Base.UseCRLContextFlagName);//事务已开启,内部事务不用处理 using (var context = new CRLDbConnectionScope()) { var db = GetDBExtend(); if (!_useCRLContext) { db.BeginTran(); } bool result; try { result = method(out error); if (!_useCRLContext) { if (!result) { db.RollbackTran(); CallContext.SetData(Base.UseCRLContextFlagName, false); return(false); } db.CommitTran(); } } catch (Exception ero) { error = "提交事务时发生错误:" + ero.Message; if (!_useCRLContext) { db.RollbackTran(); CallContext.SetData(Base.UseCRLContextFlagName, false); } return(false); } if (!_useCRLContext) { CallContext.SetData(Base.UseCRLContextFlagName, false); } return(result); } }