I am trying to create a transaction as follows:
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options)) { try { dbContext.MyTable.PartnerId = someGuid; dbContext.SaveChanges(); scope.Complete(); dbContext.AcceptAllChanges() } catch (Exception ex) { log.LogMessageToFile("Exception - ExceptionType: " + ex.GetType().ToString() + "Exception Messsage: " + ex.Message); } }
I know that if I try to insert a manully element in sql with a duplicate in a specific column, I get the following error from sql:
Cannot insert duplicate key string in object 'dbo.MyTable' with unique index 'idx_PartnerId_notnull'. The duplicate key value is (7b072640-ca81-4513-a425-02bb3394dfad).
How can I programmatically catch this exception, so I can act on it.
This is the limitation that I put in my column:
CREATE UNIQUE NONCLUSTERED INDEX idx_yourcolumn_notnull ON YourTable(yourcolumn) WHERE yourcolumn IS NOT NULL;
source share