Language: C#
Try to insert a unique item
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: }
Tags:
Comment:
Playing with different ways of wrapping an attempt to insert an unique item into a database table.
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

