catch duplicate key

Posts   
 
    
Posts: 18
Joined: 26-Jun-2006
# Posted on: 30-Aug-2006 04:43:52   

Hi,

How to catch and identify a duplicate key exception? I am using

        catch (Exception err)
        {
            MessageBox.Show("Database error \n" + err.Message,
                    "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return false;
        }

but it is too generic, could some body give me a hand?.

thanks,

Walaa avatar
Walaa
Support Team
Posts: 14987
Joined: 21-Aug-2005
# Posted on: 30-Aug-2006 07:29:21   

It depends on the error message returned from the database. so you have to parse the erro message.

Something like this:

catch (Exception ex)
{
if(ex.Message.IndexOf("PRIMARY KEY constraint") >= 0)   
{
...
}
}

Also for more specialization you may handle the ORMQueryExecutionException and check the message written in the inner exception.