public bool CreateTB_PROPERTY_MODELLByList(List<TB_PROPERTY_MODEL> entity)
{
try
{ //将集合转换成DataTable
DataTable dtTable = Untity.ListToDataTable(entity); var sqlConn = (SqlConnection)_dbContext.Database.Connection; ;
sqlConn.Open();
using (SqlTransaction transaction = sqlConn.BeginTransaction())
{
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConn, SqlBulkCopyOptions.Default, transaction))
{
bulkCopy.BatchSize = ;//多少条数据提交一次
bulkCopy.BulkCopyTimeout = ;//时间设置
bulkCopy.DestinationTableName = "TB_PROPERTY_MODEL"; //表名
try
{
//这里列一定要和数据库中的表的列要一样.和数据类型也一样。不然无法导入
foreach (DataColumn col in dtTable.Columns)
{
bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
bulkCopy.WriteToServer(dtTable);
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
LogHelper.Error(ex.Message);
throw ex.InnerException;
}
finally
{
bulkCopy.Close();
sqlConn.Close();
}
}
}
return true;
}
catch (SqlException ex)
{
LogHelper.Error(ex.Message);
throw ex.InnerException;
}
catch (DbException ex)
{
LogHelper.Error(ex.Message);
throw ex.InnerException;
}
}
/// <summary>
/// List转换成Table
/// </summary>
/// <typeparam name="T">数据实体</typeparam>
/// <param name="entitys">要转换的List</param>
/// <returns>DataTable</returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
var dt = new DataTable();
//检查实体集合不能为空
if (entitys == null || entitys.Count < )
{
return dt;
throw new Exception("需转换的集合为空");
}
//取出第一个实体的所有Propertie
Type entityType = entitys[].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
//生成DataTable的structure
//生产代码中,应将生成的DataTable结构Cache起来,此处略 foreach (PropertyInfo t in entityProperties)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(t.Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
var entityValues = new object[entityProperties.Length];
for (int i = ; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}
之前用的是EF的数据写入。感觉EF在写入的时候有点慢,可能是自己没有找到EF正确的方法。