SqlBulkCopy 批量插入List<T>

        public virtual void AddBySqlBulkCopy(IEnumerable<TEntity> entities)
        {
            List<PropertyInfo> pList = new List<PropertyInfo>();
            DataTable dt = new DataTable();
            Array.ForEach<PropertyInfo>(typeof(TEntity).GetProperties(), p =>
            {
                pList.Add(p);
                dt.Columns.Add(p.Name, p.PropertyType);
            });
            entities.ForEach(item =>
            {
                DataRow row = dt.NewRow();
                pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
                dt.Rows.Add(row);
            });
            if (dt != null && dt.Rows.Count > 0)
            {
                var dbContext = _context as DbContext;
                TableAttribute temp = (TableAttribute)typeof(TEntity).GetCustomAttributes(typeof(TableAttribute), false).First();
                using (SqlBulkCopy bulk = new SqlBulkCopy(dbContext.Database.Connection.ConnectionString))
                {
                    bulk.BatchSize = 1000;
                    bulk.BulkCopyTimeout = 100;
                    bulk.DestinationTableName = temp.Name;
                    bulk.WriteToServer(dt);
                }
            }
        }

 

posted @ 2020-12-18 17:49  Tim1027  阅读(68)  评论(0编辑  收藏  举报