EF 批量插入,sqlhelper 批量插入

需添加一个using System.Linq; 引用

public void BulkInsert<T>(string connection, string tableName, IList<T> list) { using (var bulkCopy = new SqlBulkCopy(connection)) { bulkCopy.BatchSize = list.Count; bulkCopy.DestinationTableName = tableName; var table = new DataTable(); var props = TypeDescriptor.GetProperties(typeof(T)) .Cast<PropertyDescriptor>() .Where(propertyInfo => propertyInfo.PropertyType != null && propertyInfo.PropertyType.Namespace != null && propertyInfo.PropertyType.Namespace.Equals("System")) .ToArray(); foreach (var propertyInfo in props) { bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name); table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType); } var values = new object[props.Length]; foreach (var item in list) { for (var i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } bulkCopy.WriteToServer(table); } }

 

posted @ 2016-06-16 15:32  懒懒的小易  阅读(802)  评论(0编辑  收藏  举报