当前位置    :     网站首页    /     科技 > 详情页

.NET Dapper mysql 批量新增修改

2023-08-28 17:22:57来源:博客园


(资料图)

dapper是C#程序员比较喜欢用的轻量级ORM,简单易学,只是没有批量新增以及修改(收费版有),写了如下扩展
///     /// dapper MySQL批量新增修改扩展    ///     public static class DapperExtensions    {        ///         /// 批量插入        ///         ///         ///         /// 表名        /// 数据列表        ///         /// 主键相同修改字段        /// 事务        /// insert,replace,insert ignore        ///         public static async Task BulkInsert(            this IDbConnection connection,            string tableName,            IReadOnlyCollection items,            Dictionary> dataFunc, IEnumerable? duplicateData = null, IDbTransaction? dbTransaction = null, string insert = "INSERT")        {            const int MaxBatchSize = 5000;            const int MaxParameterSize = 10000;            var batchSize = Math.Min((int)Math.Ceiling((double)MaxParameterSize / dataFunc.Keys.Count), MaxBatchSize);            var numberOfBatches = (int)Math.Ceiling((double)items.Count / batchSize);            var columnNames = dataFunc.Keys;            var insertSql = $"{insert} INTO {tableName} ({string.Join(",", columnNames.Select(e => $"`{e}`"))}) VALUES";            var sqlToExecute = new List>();            for (var i = 0; i < numberOfBatches; i++)            {                var dataToInsert = items.Skip(i * batchSize)                    .Take(batchSize);                var valueSql = GetQueries(dataToInsert, dataFunc);                sqlToExecute.Add(Tuple.Create($"{insertSql}{string.Join(",", valueSql.Item1)}", valueSql.Item2));            }            var duplicate = string.Empty;            if (duplicateData != null)            {                duplicate = $" ON DUPLICATE KEY UPDATE {string.Join(",", duplicateData.Select(d => $"`{d}`=VALUES(`{d}`)"))}";            }            foreach (var sql in sqlToExecute)            {                await connection.ExecuteAsync(sql.Item1 + duplicate, sql.Item2, commandTimeout: int.MaxValue, transaction: dbTransaction);            }        }        private static Tuple, DynamicParameters> GetQueries(            IEnumerable dataToInsert,            Dictionary> dataFunc)        {            var parameters = new DynamicParameters();            return Tuple.Create(                dataToInsert.Select(e => $"({string.Join(",", GenerateQueryAndParameters(e, parameters, dataFunc))})"),                parameters);        }        private static IEnumerable GenerateQueryAndParameters(            T entity,            DynamicParameters parameters,            Dictionary> dataFunc)        {            var paramTemplateFunc = new Func(guid => $"@p{guid:N}");            var paramList = new List();            foreach (var key in dataFunc)            {                var paramName = paramTemplateFunc(Guid.NewGuid());                parameters.Add(paramName, key.Value(entity));                paramList.Add(paramName);            }            return paramList;        }        ///         /// 批量更新        ///         ///         ///         /// 表名        /// 数据列表        ///         ///         /// 主键字段        /// 主键是否是数字类型        /// 事务        ///         public static async Task BulkUpdate(            this IDbConnection connection,            string tableName,            IReadOnlyCollection items,            Dictionary> dataFunc, Func primaryFunc, string primaryKey, bool isIntKey = true, IDbTransaction? dbTransaction = null)        {            const int MaxBatchSize = 5000;            const int MaxParameterSize = 10000;            var batchSize = Math.Min((int)Math.Ceiling((double)MaxParameterSize / dataFunc.Keys.Count), MaxBatchSize);            var numberOfBatches = (int)Math.Ceiling((double)items.Count / batchSize);            var columnNames = dataFunc.Keys;            var updateSql = $"UPDATE {tableName} SET";            var sqlToExecute = new List>();            for (var i = 0; i < numberOfBatches; i++)            {                var dataToUpdate = items.Skip(i * batchSize)                    .Take(batchSize);                var valueSql = GetUpdateQueries(dataToUpdate, dataFunc, primaryFunc, primaryKey, isIntKey);                sqlToExecute.Add(Tuple.Create($"{updateSql}{valueSql.Item1}", valueSql.Item2));            }            foreach (var sql in sqlToExecute)            {                await connection.ExecuteAsync(sql.Item1, sql.Item2, commandTimeout: int.MaxValue, transaction: dbTransaction);            }        }        private static Tuple GetUpdateQueries(            IEnumerable dataToUpdate,            Dictionary> dataFunc, Func primaryFunc, string primaryKey, bool isIntKey)        {            var paramTemplateFunc = new Func((guid, entity) =>            {                var keyValue = primaryFunc(entity);                if (!isIntKey)                {                    keyValue = $""{keyValue}"";                }                var param = $"@p{guid:N}";                var sql = $"WHEN {keyValue} THEN {param}";                return (param, sql);            }            );            var parameters = new DynamicParameters();            List sqlList = new();            foreach (var key in dataFunc)            {                var paramList = new List();                foreach (var e in dataToUpdate)                {                    var (param, sql) = paramTemplateFunc(Guid.NewGuid(), e);                    parameters.Add(param, key.Value(e));                    paramList.Add(sql);                }                sqlList.Add($"`{key.Key}`=CASE `{primaryKey}` {string.Join(" ", paramList)} END");            }            object idFunc(T p)            {                return primaryFunc(p);            }            parameters.Add("@ids", dataToUpdate.Select(idFunc));            return Tuple.Create(                $"{string.Join(",", sqlList)} WHERE `{primaryKey}` IN @ids",                parameters);        }    }
使用方法:新增:
await conn.BulkInsert(                    "userInfo",    //表名                         userinfoList,    //列表                     new Dictionary>                         {                             {"Name", u => u.Name },                             {"Age", u => u.Age },                             {"Sex", u => u.Sex },                         });
修改:
await conn.BulkUpdate("userInfo", userInfoList, new Dictionary>                        {                           {"Name", u => u.Name }                             {"Age", u => u.Age },                             {"Sex", u => u.Sex },                          }, new Func(u => u.ID), "ID");

标签:

电脑

硬件

电竞

数码

扩容卡是什么?扩容卡怎么检测? 什么内存卡好?闪迪内存卡怎么样? 大于4GB文件移动硬盘无法存储怎么办?移动硬盘不被系统识别怎么办? 移动硬盘保养有什么技巧?购买移动硬盘有什么注意事项? 手机SD卡受损怎么办?局域网计算机怎么禁用U盘?
产品

朴相民(关于朴相民的基本详情介绍)

专家谈:氧化锌系列产品在轮胎橡胶配方中的应用现状和发展趋势【SMM锌业大会】

官方回应商汤科技多部门裁员

【动力煤】煤炭储备飙升,预示煤价的稳健之路

新车 | 猛士917/豹8/新卫士等,2023成都车展50万元以上硬派风格SUV