One of my tables have a unique key and when I try to insert a duplicate record it throws an exception as expected. But I need to distinguish unique key exceptions from others, so that I can customize the error message for unique key constraint violations.
All the solutions I've found online suggests to cast ex.InnerException
to System.Data.SqlClient.SqlException
and check the if Number
property is equal to 2601 or 2627 as follows:
try
{
_context.SaveChanges();
}
catch (Exception ex)
{
var sqlException = ex.InnerException as System.Data.SqlClient.SqlException;
if (sqlException.Number == 2601 || sqlException.Number == 2627)
{
ErrorMessage = "Cannot insert duplicate values.";
}
else
{
ErrorMessage = "Error while saving data.";
}
}
But the problem is, casting ex.InnerException
to System.Data.SqlClient.SqlException
causes invalid cast error since ex.InnerException
is actually type of System.Data.Entity.Core.UpdateException
, not System.Data.SqlClient.SqlException
.
What is the problem with the code above? How can I catch Unique Key Constraint violations?