• dapper List SqlBulkCopy


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data.SqlClient;
    using System.Data;
    using Dapper;
    using DapperExtensions.Sql;
    using DapperExtensions;
    
    namespace 读取EXCEL中的内容
    {
      public  class dapperInsertBatch
        {
            /// <summary>  
            /// 批量插入功能  
            /// </summary>  
            public void InsertBatch<T>(IDbConnection conn, IEnumerable<T> entityList, IDbTransaction transaction = null) where T : class
            {
                var tblName = string.Format("dbo.{0}", typeof(T).Name);
                var tran = (SqlTransaction)transaction;
                using (var bulkCopy = new SqlBulkCopy(conn as SqlConnection, SqlBulkCopyOptions.TableLock, tran))
                {
                    bulkCopy.BatchSize = entityList.Count();
                    bulkCopy.DestinationTableName = tblName;
                    var table = new DataTable();
                    DapperExtensions.Sql.ISqlGenerator sqlGenerator = new SqlGeneratorImpl(new DapperExtensionsConfiguration());
                    var classMap = sqlGenerator.Configuration.GetMap<T>();
                    var props = classMap.Properties.Where(x => x.Ignored == false).ToArray();
                    foreach (var propertyInfo in props)
                    {
                        bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                        table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyInfo.PropertyType) ?? propertyInfo.PropertyInfo.PropertyType);
                    }
                    var values = new object[props.Count()];
                    foreach (var itemm in entityList)
                    {
                        for (var i = 0; i < values.Length; i++)
                        {
                            values[i] = props[i].PropertyInfo.GetValue(itemm, null);
                        }
                        table.Rows.Add(values);
                    }
                    bulkCopy.WriteToServer(table);
                }
            }
    
        }
    }

    --

  • 相关阅读:
    非递归的中序遍历(inorder)树 leetcode 94
    基于二叉树的抢劫问题 leetcode337
    查询二叉树的公共父结点 leetcode 236
    链表的无锁操作 (JAVA)
    kexec 内核快速启动流程分析
    最近几天严重营养不良。。。
    Better Me
    《大四上寒假总结》--3.10
    《计算机网络》学习总结
    记录
  • 原文地址:https://www.cnblogs.com/runliuv/p/10578839.html
Copyright © 2020-2023  润新知