I'm trying to update a table with a List<T>
. I created an EnumExtension class and created a method which converts my Enumerable to a DataTable:
public static DataTable AsDataTable<T>(this IEnumerable<T> data)...
And then I started creating a method which should use BulkCopy to insert or update my table, using the enumerable. Right now, it's written like this:
public void BulkInsertOrUpdate(DatabaseEnum database, IEnumerable<Object> enumerable, string TableName)
{
var connection = this.GetSqlConnection(database);
var transaction = connection.BeginTransaction();
using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))
{
bulkCopy.BatchSize = 100;
bulkCopy.DestinationTableName = TableName;
try
{
bulkCopy.WriteToServer(enumerable.AsDataTable());
}
catch (Exception)
{
transaction.Rollback();
connection.Close();
}
}
transaction.Commit();
}
(OBS: Method GetSqlConnection creates and opens my connection using the appropiate connection string.)
But I don't know how to create the update feature. Is there a simple way to do so, with an efficient code? I'm fond of BulkCopy, but I can try another method, hopefully not hurting my architecture (and, ultimately, I'll have to make this sacrifice if I can't find a way).
Thanks for your attention, I'm ready to answer doubts about my situation.