public static async Task <object> ExecuteCommandAsync(DbConnection conn, string commandText , CommandResultTypeEnum commandResultType = CommandResultTypeEnum.Table, CommandType commandType = CommandType.Text , IEnumerable <DbParameter> parameters = null, Action <DbCommand> onCreateCommand = null) { if (conn == null) { throw new ArgumentNullException("conn"); } if (string.IsNullOrEmpty(commandText)) { throw new ArgumentNullException("commandText"); } if (conn.State != System.Data.ConnectionState.Open) { await conn.OpenAsync(); } using (var cmd = GetCommand(conn, commandText, commandType, (parameters != null ? parameters.ToArray() : null))) { if (onCreateCommand != null) { onCreateCommand(cmd); } object result = null; switch (commandResultType) { case CommandResultTypeEnum.Table: { DataTable table = null; using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { // Inicializar DataTable if (table == null) { table = new DataTable(); for (int i = 0; i < reader.FieldCount; i++) { table.Columns.Add(reader.GetName(i), typeof(object)); } } // Criar linha na datatable var row = table.NewRow(); for (int i = 0; i < reader.FieldCount; i++) { var obj = await reader.GetFieldValueAsync <object>(i); row[i] = obj; } table.Rows.Add(row); } } result = table; } break; case CommandResultTypeEnum.NonQuery: { result = await cmd.ExecuteNonQueryAsync(); } break; case CommandResultTypeEnum.Reader: { result = await cmd.ExecuteReaderAsync(); } break; default: throw new ApplicationException(string.Format("Invalid ExecuteCommand result type: '{0}'", commandResultType)); } if (cmd.Parameters != null) { cmd.Parameters.Clear(); } return(result); } }
public CommandResult(T result, CommandResultTypeEnum type) { Result = result; Type = type; }
public static async Task <object> ExecuteCommandAsync(string connectionString, string command, CommandResultTypeEnum commandResultType = CommandResultTypeEnum.Table, CommandType commandType = CommandType.Text, IEnumerable <DbParameter> parameters = null, string providerName = "System.Data.SqlClient", Action <DbCommand> onCreateCommand = null) { if (string.IsNullOrEmpty(connectionString)) { throw new ArgumentNullException("connectionString"); } using (var conn = GetConnection(connectionString, providerName)) { return(await ExecuteCommandAsync(conn, command, commandResultType, commandType, parameters, onCreateCommand)); } }