本文引用了来自
http://elegantcode.com/ 的代码。
- 大家经常抱怨EF插入批量数据非常慢,可以简单的通过设置:
1
2
| context.Configuration.AutoDetectChangesEnabled = false;
context.Configuration.ValidateOnSaveEnabled = false;
|
EF6也可以用
来优化性能,但有的同学觉得依然不够快,以至于通过直接写SQL来插入数据,但这样会让代码看起来很不爽。
- 下面提供一个更好一些的方法,这个方法是用了BCP,是微软专门为批量数据导入导出SQLServer设计的,废话不多说,直接看代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| public static 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.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);
}
}
|
1
2
| var imports = new List<Product>();
BulkInsert(context.Database.Connection.ConnectionString, "Products", imports);
|
- 这个方法适用于实体的字段名和数据库表之间的列名相同的情况,当然EF的CodeFirst模式下默认就是这样的,可以运行的很好。
- **有多快呢?**引用一张图:

那是相当的给力,试试看啦。