批量插入bulkcopy

时间:2022-07-06 03:35:35
 public static void InsertBatch<T>(IDbConnection conn, IEnumerable<T> entityList, string tblName, IDbTransaction transaction = null) where T : class
        {
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            using (var bulkCopy = new SqlBulkCopy(conn as SqlConnection))
            {
                var enumerable = entityList as T[] ?? entityList.ToArray();
                bulkCopy.BatchSize = enumerable.Count();
                bulkCopy.DestinationTableName = tblName;
                var table = new DataTable();
                DapperExtensions.Sql.ISqlGenerator sqlGenerator = new SqlGeneratorImpl(new DapperExtensionsConfiguration());
                var classMap = sqlGenerator.Configuration.GetMap<T>();
                IPropertyMap[] props;
                if (tblName == "RepayRecords")
                {
                    props = classMap.Properties.Where(x => x.Ignored == false && x.ColumnName != "DeductWays").ToArray();
                }
                else
                {
                    props = classMap.Properties.Where(x => x.Ignored == false).ToArray();
                }

foreach (var propertyInfo in props)
                {
                    bulkCopy.ColumnMappings.Add(批量插入bulkcopypropertyInfo.Name, 批量插入bulkcopypropertyInfo.Name);
                    table.Columns.Add(批量插入bulkcopypropertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyInfo.PropertyType) ?? propertyInfo.PropertyInfo.PropertyType);
                }
                var values = new object[props.Count()];
                foreach (var itemm in enumerable)
                {
                    for (var i = 0; i < values.Length; i++)
                    {
                        values[i] = props[i].PropertyInfo.GetValue(itemm, null);
                    }
                    table.Rows.Add(values);
                }
                bulkCopy.WriteToServer(table);
            }
        }