.net EF大数据导入性能解决方案:
构建测试数据,插入表User
List<User> list = new List<User>();
for (int i = 0; i < 10000; i++)
{
list.Add(new User
{
id = i,
name = i.ToString()
});
}
方案一:使用第三方插件 Z.EntityFramework.Extension
1、nuget安装插件;
2、使用BulkInsert方法添加数据;
3、使用BulkSaveChanges提交;
示例代码:
public void ExtInserts<TEntity>(List<TEntity> list) where TEntity : class
{
DbContext db = new DbContext("ProjectDbContext");
db.BulkInsert(list);
db.BulkSaveChanges();
}
方案二:使用SqlBulkCopy
public void ExtInserts<TEntity>(List<TEntity> list) where TEntity : class,new()
{
DataTable dt = list.ToTable();
string str = System.Configuration.ConfigurationManager.ConnectionStrings["ProjectDbContext"].ToString();//获取数据库连接字符串
using (SqlBulkCopy sbc = new SqlBulkCopy(str))
{
Type type = typeof(TEntity);
//设置要插入的表名
sbc.DestinationTableName = type.Name;
TEntity s = new TEntity();
PropertyInfo[] ps = s.GetType().GetProperties();
foreach (PropertyInfo pi in ps)
{
sbc.ColumnMappings.Add(pi.Name, pi.Name);//与服务器数据库列名映射,
}
//执行
sbc.WriteToServer(dt);
}
}