I use System.Data.Common.DbCommand to insert a new row to database. The point is, that this row already exists.
try
{
[...]
DbCommand insertCommand = [...]
insertCommand.ExecuteScalar();
[...]
}
catch (System.Exception exception)
{
[...]
throw;
}
If I would catch explicitly System.Data.SqlClient.SqlException I could evaluate the ErrorNumber like follow.
try
{
//insertion code
}
catch(SqlException ex)
{
if(ex.Number == 2627)
{
//Violation of primary key. Handle Exception
}
}
The ErrorNumber 2627 in the context of a SqlException means Violation of Unique Key. See https://msdn.microsoft.com/en-us/library/ms151757%28v=sql.110%29.aspx
So far so good. Because I am working with DbCommand and therefore with different kinds of Relational Database Management Systems, I am searching for a more generic manner to catch such a violation of unique key constraint.
Thanks for Help.
To handle unique constraint violations: Catch uniqueness exceptions thrown by the database at the lowest level possible — in the UnitOfWork class. Convert them into Result.
A unique key is a group of one or more than one fields or columns of a table which uniquely identify database record. A unique key is the same as a primary key, but it can accept one null value for a table column. It also cannot contain identical values.
A unique constraint violation occurs when an UPDATE or INSERT statement attempts to insert a record with a key that already exists in the table. Take a look at the package that is throwing the error.
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.
I'm afraid there is no built-in generic solution for that. As a workaround, you could create a wrapper for Execute...
:
public static int ExecuteWithNiceExceptions(this IDbCommand cmd)
{
try
{
return cmd.ExecuteNonQuery();
}
catch(SqlException ex)
{
if (ex.Number == 2627)
{
throw new PrimaryKeyViolationException(cmd, ex);
}
else
{
throw;
}
}
catch (OleDbException ex)
{
...
}
...
}
That way, you would "convert" the different, implementation-specific exceptions into generic, meaningful exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With