/// <summary> /// 将方法调用打包,使只用一个数据连接 /// 同CRLDbConnectionScope /// </summary> /// <param name="action"></param> public void PackageMethod(Action action) { using (var context = new DbConnectionScope()) { try { action(); } catch (Exception ero) { context.Dispose(); throw ero; } } }
/// <summary> /// 使用DbTransaction封装事务,不能跨库 /// 请将数据访问对象写在方法体内 /// 可嵌套调用 /// </summary> /// <param name="method"></param> /// <param name="error"></param> /// <param name="isolationLevel"></param> /// <returns></returns> public bool PackageTrans(TransMethod method, out string error, System.Data.IsolationLevel isolationLevel = System.Data.IsolationLevel.ReadCommitted) { error = ""; var _useCRLContext = CallContext.GetData <bool>(Base.UseCRLContextFlagName);//事务已开启,内部事务不用处理 using (var context = new DbConnectionScope()) { var db = GetDBExtend(); if (!_useCRLContext) { db.BeginTran(isolationLevel); } 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); } }