Last active
March 26, 2016 10:45
-
-
Save fatagun/ec44bc617e728e8c974d to your computer and use it in GitHub Desktop.
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
public static class IEnumerableExtensions | |
{ | |
public static DataTable AsDataTable<T>(this IEnumerable<T> data) | |
{ | |
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T)); | |
var table = new DataTable(); | |
foreach (PropertyDescriptor prop in properties) | |
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); | |
foreach (T item in data) | |
{ | |
DataRow row = table.NewRow(); | |
foreach (PropertyDescriptor prop in properties) | |
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value; | |
table.Rows.Add(row); | |
} | |
return table; | |
} | |
} | |
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeConnectionString"].ConnectionString)) | |
{ | |
connection.Open(); | |
SqlTransaction transaction = connection.BeginTransaction(); | |
using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction)) | |
{ | |
bulkCopy.BatchSize = 100; | |
bulkCopy.DestinationTableName = "dbo.Person"; | |
try | |
{ | |
bulkCopy.WriteToServer(listPerson.AsDataTable()); | |
} | |
catch (Exception) | |
{ | |
transaction.Rollback(); | |
connection.Close(); | |
} | |
} | |
transaction.Commit(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment