简体   繁体   中英

Problem catching SqlException 547 with DeleteConfirmed class in ASP.NET Core MVC Controller

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM