简体   繁体   English

在 ASP.NET Core MVC 控制器中使用 DeleteConfirmed 类捕获 SqlException 547 的问题

[英]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 ).我在具有相应Model和所有视图( Index, Detail, Edit and Delete )的简单数据库表( Products )上有标准的 MVC 控制器。 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.我已经修改了我的控制器中的DeleteConfirmed类,因此我可以捕获当有人尝试删除具有外键约束的记录时发生的SqlException

Here is my DeleteConfirmed class in Controller now:这是我现在在控制器中的DeleteConfirmed类:

// 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_...". SqlException: DELETE 语句与 REFERENCE 约束“FK_...”冲突。 The conflict occurred in database "Store", table "...", column '...'.冲突发生在数据库“Store”、表“...”、“...”列中。 The statement has been terminated.该语句已终止。

Raw exception details shows that it's really exception 547:原始异常详细信息显示它确实是异常 547:

Microsoft.Data.SqlClient.SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "...". Microsoft.Data.SqlClient.SqlException (0x80131904):DELETE 语句与 REFERENCE 约束“...”冲突。 The conflict occurred in database "Store", table "...", column '..'.冲突发生在数据库“Store”、表“...”、“...”列中。 The statement has been terminated.该语句已终止。 at Microsoft.Data.SqlClient.SqlCommand.<>c.b__164_0(Task`1 result) ... ... Error Number:547,State:0,Class:16在 Microsoft.Data.SqlClient.SqlCommand.<>c.b__164_0(Task`1 result) ... ...错误编号:547,状态:0,类: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.因此,与其等待异常发生并对其做出反应,不如主动检查要删除的Product是否与另一个实体具有外键关系。 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.当您尝试从Products Table 中删除一行时,它知道同一行在另一个 Table 中有一些相关的行(它在“FK_Products_(...)”异常错误的末尾说这个第二个表的名称.

So, you need to delete from the 2nd Table first and then delete from Product table.因此,您需要先从第二个表中删除,然后再从Product表中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET Core MVC中捕获异常 - Catching exceptions in ASP.NET Core MVC ASP.NET MVC:控制器未捕获自定义Identity UserStore类中引发的异常 - ASP.NET MVC: Controller not catching exception thrown in custom Identity UserStore class SqlException:asp.net mvc 核心中@VariableName 附近的语法不正确 - SqlException: Incorrect syntax near @VariableName in asp.net mvc core 控制器中的ASP.NET Core MVC Subaction - ASP.NET Core MVC Subaction in a controller Asp.Net Mvc Core 中的无会话控制器 - Sessionless controller in Asp.Net Mvc Core ASP.NET Core MVC:编辑用户,将数据从视图传递到 controller 时出现问题,身份 - ASP.NET Core MVC : edit user, problem with passing data from view to controller ,identity 我在使用 Visual Studio 生成带有 ASP.NET Core 6 MVC 项目视图的 controller 时遇到问题 - I have a problem generating a controller with views in ASP.NET Core 6 MVC project using Visual Studio 我如何告诉 MVC 中间件我的 class 是 ASP.NET Core 中的一个 Controller? - How do I tell the MVC middleware that my class is a Controller in ASP.NET Core? ASP.NET Core MVC 模型 - SqlException 无法为标识列插入显式值 - ASP.NET Core MVC models - SqlException cannot insert explicit value for identity column 在 ASP.NET Core MVC 中通过控制器从数据库中读取信息 - Reading information from database by controller in ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM