废话不多说,直接上代码
public void BulkInsert<T>(IList<T> entities,int timeout=0) where T :class
{
var con = Database.Connection as SqlConnection;
if (con == null) return;
if (con.State != ConnectionState.Open)
con.Open();
try {
string tablename = null, columnname = null;
var tableattr = typeof(T).GetCustomAttribute<TableAttribute>();
if (tableattr != null)
tablename = tableattr.Name;
else
tablename = typeof(T).Name;
using (var bulkCopy = new SqlBulkCopy(con) { DestinationTableName = tablename })
{
var properties = typeof(T).GetProperties().Where(p => !p.GetGetMethod().IsVirtual).ToArray();
var table = new System.Data.DataTable();
foreach (var property in properties)
{
Type propertyType = property.PropertyType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
propertyType = Nullable.GetUnderlyingType(propertyType);
}
var columnattr = property.GetCustomAttribute<ColumnAttribute>();
if (columnattr != null)
columnname = columnattr.Name;
else
columnname = property.Name;
table.Columns.Add(new System.Data.DataColumn(property.Name, propertyType));
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(property.Name, columnname));
}
foreach (var entity in entities)
{
table.Rows.Add(properties.Select(p => p.GetValue(entity, null)).ToArray());
}
if (timeout != 0)
bulkCopy.BulkCopyTimeout = timeout;
bulkCopy.WriteToServer(table);
}
}
catch (Exception e)
{
//System.Diagnostics.Debug.WriteLine(e);
throw e;
}
finally
{
con.Close();
}
}
}