What are the possible error codes that sql / c# returns when violating UNIQUE KEY constraint?


This Content is from Stack Overflow. Question asked by devludo

What are the possible error codes that SQL or c# throws when violating a UNIQUE KEY constraint when inserting or editing the database?

What i want to achieve is:

  • handle the UNIQUE constraint in my app.
  • Now i am simpy relying on the SQL engine throwing the error and then handling it.

Here is what i am doing (i do not know if this is good practice or should i use specific codes, that is why i am asking):

   await context.SaveChangesAsync();
catch (Exception ex)
   if (ex.InnerException.Message.Contains("UNIQUE KEY"))
        // throw error for unique key

Is this the right way of doing it?


This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?