0

How to best handle Unique constraint during data insert/update?

I have a table that have a field that I put in Unique constraint key set to yes. When the user click the Register Error button, I got the following error:

Violation of UNIQUE KEY constraint 'UK_Email.tbl_User'. Cannot insert duplicate key in object 'dbo.ProjectDAL'. The statement has been terminated.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'IX_emailGroups'. Cannot insert duplicate key in object 'dbo.emailGroups'. The statement has been terminated.

What is the best way to handle unique errors as shown above? as I m trying This

try
{
.........
}
catch(Exceptiion e)
{
       catch (Exception ex)
        {
            if (ex.Message.Contains('UK_Email_tbl_User'))
            {
                lblMsg.Text = "Record already exist.";
            }

            else
            {
                lblMsg.Text = "Something Happened";
            }
        } 
sstan
  • 35,425
  • 6
  • 48
  • 66
  • 1
    Don't you think you should handle it in the database operation you are carrying out? Like `IF NOT EXISTS (SELECT * FROM YourTable WHERE <>)` – Chaos Legion Jun 02 '16 at 12:22
  • What I usually do is have my code written in such a way that this exception should not happen in the first place (check for the existence of a record *before* inserting or updating). The unique constraint in the database is then used more like a safety net to protect the data in case my program has a bug. In that case, I don't try to handle the exception gracefully. – sstan Jun 02 '16 at 12:24
  • 1
    @sstan In a highly concurrent environment it's impossible to rely on checking for the existence of a record _before_ inserting. So UNIQUE constraint violation should be processed in a normal business workflow. – Serg Jun 02 '16 at 12:54
  • @Serg: Absolutely! thanks for pointing that out. – sstan Jun 02 '16 at 13:32

0 Answers0