/// <summary> /// 执行 SQL 命令 /// </summary> /// <typeparam name="T">返回的元素类型</typeparam> /// <param name="command">SQL 命令</param> /// <param name="func">执行命令的委托</param> /// <param name="wasClosed">执行SQL命令后是否自动关闭连接</param> /// <param name="interceptException">指示外层是否捕获异常</param> /// <returns></returns> protected virtual async Task <T> DoExecuteAsync <T>(IDbCommand command, Func <System.Data.Common.DbCommand, Task <T> > func, bool wasClosed, bool interceptException = true) { T TResult = default(T); try { if (command.Transaction != null && _transaction != null && command.Transaction != _transaction) { throw new XFrameworkException("DoExecute: IDbCommand.Transaction does not equals to current transaction."); } if (command.Connection != null && _connection != null && command.Connection != _connection) { throw new XFrameworkException("DoExecute: IDbCommand.Connection does not equals to current connection."); } if (command.Connection == null) { command.Connection = await this.CreateConnectionAsync(); } if (command.Connection.State != ConnectionState.Open) { await((DbConnection)command.Connection).OpenAsync(); } if (interceptException) { DbInterception.OnExecuting(command); } TResult = await func((System.Data.Common.DbCommand) command); if (interceptException) { DbInterception.OnExecuted(command); } } catch (DbException e) { // 外层不捕获异常,由内层Func去捕获 if (interceptException) { DbInterception.OnException(new DbCommandException(e.Message, e, command)); } throw; } finally { if (command != null) { command.Dispose(); } if (wasClosed) { this.InternalDispose(); } } return(TResult); }
/// <summary> /// 执行 SQL 命令 /// </summary> protected virtual T DoExecute <T>(IDbCommand command, Func <IDbCommand, T> func, bool wasClosed, bool interceptException = true) { T TResult = default(T); try { if (command.Transaction != null && _transaction != null && command.Transaction != _transaction) { throw new XFrameworkException("DoExecute: IDbCommand.Transaction does not equals to current transaction."); } if (command.Connection != null && _connection != null && command.Connection != _connection) { throw new XFrameworkException("DoExecute: IDbCommand.Connection does not equals to current connection."); } if (command.Connection == null) { command.Connection = this.CreateConnection(); } if (command.Connection.State != ConnectionState.Open) { if (string.IsNullOrEmpty(command.Connection.ConnectionString)) { command.Connection.ConnectionString = _connString; } command.Connection.Open(); } if (interceptException) { DbInterception.OnExecuting(command); } TResult = func(command); if (interceptException) { DbInterception.OnExecuted(command); } } catch (DbException e) { // 外层不捕获异常,由内层Func去捕获 if (interceptException) { DbInterception.OnException(new DbCommandException(e.Message, e, command)); } throw; } finally { if (command != null) { command.Dispose(); } if (wasClosed) { this.InternalDispose(); } } return(TResult); }