New Snippet New Snippet Recent Snippets Recent Snippets My Snippets My Snippets Web Code Search Snippets Search
Sign inor Register
Language: C#

Try to insert a unique item

62 Views
Copy Code Show/Hide Line Numbers
   1:  private static bool AttemptInsertUniqueItem<T>(T item, Action<T> insert)
   2:  {
   3:      bool success = false;
   4:   
   5:      try
   6:      {
   7:          insert(item);
   8:          success = true;
   9:      }
  10:      catch (SqlException sqlEx)
  11:      {
  12:          if (sqlEx.Number != 2601 && sqlEx.Number != 2627)
  13:          {
  14:              // Not a UNIQUE index violation or primary key violation.
  15:              throw;
  16:          }
  17:      }
  18:   
  19:      return success;
  20:  }
  21:   
  22:  private static int TryInsertUniqueItem<T>(ref T item, Func<T, int> insert, Func<T, T> getExisting)
  23:  {
  24:      int rows = 0;
  25:   
  26:      try
  27:      {
  28:          rows = insert(item);
  29:      }
  30:      catch (SqlException sqlEx)
  31:      {
  32:          if (sqlEx.Number == 2601 || sqlEx.Number == 2627)
  33:          {
  34:              // UNIQUE index violation or primary key violation; get the existing item.
  35:              item = getExisting(item);
  36:          }
  37:          else
  38:          {
  39:              Console.WriteLine(sqlEx);
  40:              throw;
  41:          }
  42:      }
  43:   
  44:      return rows;
  45:  }
by Jon Sagara
  May 26, 2010 @ 11:20pm
Tags:
Comment:
Playing with different ways of wrapping an attempt to insert an unique item into a database table.

Add a comment


Report Abuse
brought to you by:
West Wind Techologies


If you find this site useful and use it frequently please consider making a donation to support this free service.
Donate