title: INSERT object or UPDATE if it already exists using BulkCopy (C#, SQL)
body: <p>I'm trying to update a table with a <code>List&lt;T&gt;</code>. I created an EnumExtension class and created a method which converts my Enumerable to a DataTable:</p>
  
  <pre><code>public static DataTable AsDataTable&lt;T&gt;(this IEnumerable&lt;T&gt; data)...
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>public void BulkInsertOrUpdate(DatabaseEnum database, IEnumerable&lt;Object&gt; 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();
      }
  </code></pre>
  
  <p>(OBS: Method GetSqlConnection creates and opens my connection using the appropiate connection string.)</p>
  
  <p>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).</p>
  
  <p>Thanks for your attention, I'm ready to answer doubts about my situation.</p>