1

I have standard MVC Controller on simple database table (Products) with corresponding Model and all Views (Index, Detail, Edit and Delete). All functionalities works without problem if record doesn't have foreign key constraint.

I've modified DeleteConfirmed class in my Controller so I can catch SqlException that happens when someone tries to delete record that has foreign key constraint.

Here is my DeleteConfirmed class in Controller now:

// POST: Products/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    try
    {
        var products = await _context.Products.FindAsync(id);
        _context.Products.Remove(products);   
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));             
    }
    catch (SqlException ex) when (ex.Number == 547)
    {
        return Content("Product cannot be deleted because...");
    }    
}

But it still throws exception:

An unhandled exception occurred while processing the request. SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_...". The conflict occurred in database "Store", table "...", column '...'. The statement has been terminated.

Raw exception details shows that it's really exception 547:

Microsoft.Data.SqlClient.SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "...". The conflict occurred in database "Store", table "...", column '..'. The statement has been terminated. at Microsoft.Data.SqlClient.SqlCommand.<>c.b__164_0(Task`1 result) ... ... Error Number:547,State:0,Class:16

What am I doing wrong?

2 Answers 2

1

What's wrong is the logic of your code.

Exceptions are supposed to be exceptional, not something that you expect to happen in the normal flow of your application. A foreign-key violation is something you would expect as a matter of course, hence not an exception.

So, instead of waiting for the exception to happen and reacting to it, be proactive by checking to see if the Product that is to be deleted has a foreign-key relationship with another entity. If so, don't try to do the delete, and show your "Product cannot be deleted" message.

2
  • I will do that, and it will solve the problem. But why can't I have simple text message displayed instead of known exception?
    – Hrvoje
    Sep 16, 2020 at 18:18
  • But if you check the product has not any relationship and before try to delete it another process add a relationship with the product. Wouldn't you get the exception? So you are making an extra query and you will not be sure you will can delete it. Dec 1, 2023 at 11:50
0

You are trying to Delete the record from a Table which has a reference in another Table.

When you try to delete a row from Products Table, it comes to know that the same row has some related row in another Table (it says the name of this 2nd table at the end of the "FK_Products_(...)" exception error.

So, you need to delete from the 2nd Table first and then delete from Product table.

2
  • Sorry that my answer was not helpful, I didn't realize your question's focus was on the exception and not on the constraint itself
    – Rute Lemos
    Sep 17, 2020 at 3:44
  • 1
    I didn't give you -1 , and I think your answer is also helpful.
    – Hrvoje
    Sep 17, 2020 at 7:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.