-
-
Save jmreynolds/a5956802d5986d071de5 to your computer and use it in GitHub Desktop.
Use SQLBulkLoad with linq-toSQL in LinqPad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add this to LinqPad "C# Program" | |
// Example use: | |
// Insead of this: (create a List<CS_POSITION>) | |
// CS_POSITIONs.InsertOnSubmit(position); | |
// This: | |
// positions.Add(position); | |
// | |
// Then instead of this: | |
// SubmitChanges() | |
// This: | |
// BulkInsertAll<CS_POSITION>(positions) | |
void BulkInsertAll<T>(List<T> entities) | |
{ | |
var conn = (SqlConnection) this.Connection; | |
Type t = typeof(T); | |
var tableAttribute = (TableAttribute)t.GetCustomAttributes(typeof(TableAttribute),false).Single(); | |
var bulkCopy = new SqlBulkCopy(conn) { DestinationTableName = tableAttribute.Name }; | |
var properties = t.GetMembers().Where(p=>{ | |
var columnAttribute = Attribute.GetCustomAttribute(p,typeof (ColumnAttribute)) as ColumnAttribute; | |
if (columnAttribute != null) return true; | |
return false; | |
}).ToArray(); | |
var table = new DataTable(); | |
foreach (var property in properties) | |
{ | |
Type propertyType = ((FieldInfo)property).FieldType; | |
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) | |
{ | |
propertyType = Nullable.GetUnderlyingType(propertyType); | |
} | |
table.Columns.Add(new DataColumn(property.Name, propertyType)); | |
} | |
foreach (var entity in entities) | |
{ | |
var cols = properties.Select( property => { | |
var field = (FieldInfo) property; | |
var o = field.GetValue(entity); | |
if (o==null) | |
return DBNull.Value; | |
else | |
return o; | |
}).ToArray(); | |
table.Rows.Add(cols); | |
} | |
conn.Open(); | |
bulkCopy.BulkCopyTimeout = 0; | |
bulkCopy.WriteToServer(table); | |
conn.Close(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
FYI if your source class has Properties (not just Fields) you'll need to add support for them. The casts to
FieldInfo
will fail because the givenMemberInfo
s aren't properties.Here's a fork (of a fork!): https://gist.github.com/DavidPx/353a20c2f86530cadc63627e625bd9f4