I have the following code in a library to perform a delete operation on database records. My code uses the Dapper library. The error is happening when I call the Dapper Execute() method.
Some of the database table records can not be deleted because they are referenced by related records in other tables. When a record can't be deleted, the database error "The DELETE statement conflicted with the REFERENCE constraint" happens (as expected). This error causes a System.Data.SqlClient.SqlException when calling Execute, and this exception crashes my program.
I wrote a try/catch to handle this error, but the program still crashes in the try and doesn't move to the catch block. It seems that maybe Execute() doesn't throw the exception? I've also tried using the Query() method with the same outcome. I am at a loss as to how I can catch and deal with this exception!
private IDbConnection db;
public Repository(string connectionString)
{
db = new SqlConnection(connectionString);
}
public void DeletePerson(string PersonID)
{
string query = "DELETE FROM PERSON WHERE PersonID = @PersonID";
try
{
db.Execute(query, new { PersonID }); //program crashes here b/c of SqlException
}
catch (Exception ex)
{
throw ex;
}
}
Here is the code that calls this method (from a different project). It is also in a try/catch, but the catch is never reached.
string id = "BELWIT";
try
{
conn.DeletePerson(id);
}
catch
{
MessageDialog errorMsg = new MessageDialog("Delete failed.");
errorMsg.ShowAsync();
}