SqlBulkCopy 批量插入List<T>
public virtual void AddBySqlBulkCopy(IEnumerable<TEntity> entities) { List<PropertyInfo> pList = new List<PropertyInfo>(); DataTable dt = new DataTable(); Array.ForEach<PropertyInfo>(typeof(TEntity).GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); }); entities.ForEach(item => { DataRow row = dt.NewRow(); pList.ForEach(p => row[p.Name] = p.GetValue(item, null)); dt.Rows.Add(row); }); if (dt != null && dt.Rows.Count > 0) { var dbContext = _context as DbContext; TableAttribute temp = (TableAttribute)typeof(TEntity).GetCustomAttributes(typeof(TableAttribute), false).First(); using (SqlBulkCopy bulk = new SqlBulkCopy(dbContext.Database.Connection.ConnectionString)) { bulk.BatchSize = 1000; bulk.BulkCopyTimeout = 100; bulk.DestinationTableName = temp.Name; bulk.WriteToServer(dt); } } }