最近做的一个ABP项目需要批量导入数据到mysql,网上查找了各种资料都没实现,然后根据查找的资料整合了一下,方法是用list集合转化成DataTable然后使用MySqlBulkCopy方式批量上传数据,速度明显快了许多
public int ListToDataTable<T>(List<T> list,string name)
{
int count = 0;
if (list == null || list.Count == 0)
{
return 0;
}
//获取T下所有的属性
Type entityType = list[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
DataTable dt = new DataTable(name);
for (int i = 0; i < entityProperties.Length; i++)
{
dt.Columns.Add(entityProperties[i].Name);
}
foreach (var item in list)
{
if (item.GetType() != entityType)
{
throw new Exception("要转换集合元素类型不一致!");
}
//创建一个用于放所有属性值的数组
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(item, null);
}
dt.Rows.Add(entityValues);
}
var config = _iocResolver.Resolve<IAbpStartupConfiguration>();
try
{
count = BulkInsert.MySqlBulkInsert(dt, config.DefaultNameOrConnectionString);
}
catch (Exception e)
{
return count;
}
return count;
}
本地测试导入数据
MYSQL批量导入dll