public static int Update(this SqlConnection connection, string table, KeyValuePairs kvs, int[] ids) { if (string.IsNullOrWhiteSpace(table)) { throw new ArgumentNullException(nameof(table), "数据表不能为空"); } if (kvs == null || kvs.Any(kv => kv.Key == "Id")) { throw new ArgumentNullException(nameof(kvs), "要更新的列不能为空,并且不能包含Id列"); } if (ids == null || !ids.Any()) { throw new ArgumentNullException(nameof(ids), "ID数组不能为空"); } var columns = new List <string>(); var param = new DynamicParameters(); param.Add("Ids", ids); foreach (var kv in kvs.Where(kv => kv.Key != "Id")) { columns.Add($"{kv.Key}=@{kv.Key}"); param.Add(kv.Key, kv.Value); } var sql = $"UPDATE [{table}] SET {string.Join(",", columns)} WHERE Id in @Ids"; return(connection.Execute(sql, param)); }
public static int Update(this SqlConnection connection, string table, KeyValuePairs kvs, MySearchUtil util = null, SqlTransaction trans = null) { if (string.IsNullOrWhiteSpace(table)) { throw new ArgumentNullException(nameof(table), "数据表不能为空"); } if (kvs == null || kvs.Any(kv => kv.Key == "Id")) { throw new ArgumentNullException(nameof(kvs), "要更新的列不能为空,并且不能包含Id列"); } util = util ?? new MySearchUtil(); var cols = string.Join(",", kvs.Where(kv => kv.Key != "Id").Select(kv => $"{kv.Key}=@{kv.Key}")); var where = util.GetWhere(); var param = util.GetParam(); var sql = $"UPDATE {table} SET {cols} WHERE {where}"; return(connection.Execute(sql, param, trans)); }