Skip to content

Instantly share code, notes, and snippets.

@jmreynolds
Forked from oshea00/BulkInsertAll.cs
Last active September 8, 2023 10:48
Show Gist options
  • Save jmreynolds/a5956802d5986d071de5 to your computer and use it in GitHub Desktop.
Save jmreynolds/a5956802d5986d071de5 to your computer and use it in GitHub Desktop.
Use SQLBulkLoad with linq-toSQL in LinqPad
// 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();
}
@wizaerd
Copy link

wizaerd commented Jun 5, 2018

I know this is 2 years old, but I only just found it, and I have a question. How would I use this to insert data via LINQPad, but using a linked server? The connection string is only for the first database, and not necessarily any linked DBs...

@DavidPx
Copy link

DavidPx commented Jan 15, 2020

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 given MemberInfos aren't properties.

Here's a fork (of a fork!): https://gist.github.com/DavidPx/353a20c2f86530cadc63627e625bd9f4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment