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";
}
}