I am using System.Data.Common.DbCommand to insert a new row into the database. The fact is that this line already exists.
try { [...] DbCommand insertCommand = [...] insertCommand.ExecuteScalar(); [...] } catch (System.Exception exception) { [...] throw; }
If I explicitly caught System.Data.SqlClient.SqlException, I could evaluate ErrorNumber as shown below.
try { //insertion code } catch(SqlException ex) { if(ex.Number == 2627) { //Violation of primary key. Handle Exception } }
ErrorNumber 2627 in the context of SqlException means "Unique Key Violation". See https://msdn.microsoft.com/en-us/library/ms151757%28v=sql.110%29.aspx
So far so good. Since I work with DbCommand and therefore with various types of relational database management systems, I am looking for a more general way to catch this violation of a unique key restriction.
Thanks for the help.
c # exception sqlexception
kbisang
source share