在ASP.NET MVC中删除前检查引用完整性违例 [英] Checking for Referential Integrity Violation before deletion in ASP .NET MVC

查看:241
本文介绍了在ASP.NET MVC中删除前检查引用完整性违例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象标签链接到一大堆其他对象。我正在尝试处理此对象的删除。我不想删除标签,如果它与任何其他对象相关联。

I have an object Tag that is linked to a whole bunch of other objects. I am attempting to handle the Delete for this object. I simply don't want to delete the tag if it is associated to any other objects.

目前我正在解决这个问题:

At the moment I am solving it like this:

if(tag.Stands.Count == 0 && tag.Skids.Count == 0
   && tag.Panels.Count == 0 && tag.Devices.Count == 0
   && tag.Cables.Count == 0 && tag.JunctionBoxes.Count == 0)
{
    _db.Tags.DeleteObject(tag);
    _db.SaveChanges();
}

如果我不检查所有这些事情,我显然得到一个参考约束错误,例如

If I don't check for all these things, I obviously get a reference constraint error, e.g.


System.Data.SqlClient.SqlException:DELETE语句与参考约束FKStandTag237968冲突

System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FKStandTag237968".

我知道解决这个问题的方法是使用级联删除,但实际的业务逻辑是标签不应该被删除与任何其他对象相关联。

I know a way to get around this is with cascading deletes but it is actual business logic that tags shouldn't be deleted if they are associated to any other object.

有没有办法使用实体框架,我可以检查我不会在尝试保存之前破坏DB上的任何约束删除?

Is there a way using the Entity Framework that I can check that I won't break any constraints on the DB before attempting to save a delete? Something along the lines of _db.IsValidToDelete(object)?

推荐答案

拥有这样的方法( _db.IsValidToDelete(object))不会保证您可以安全地删除。您的应用程序是一个多用户应用程序。所以一个用户可以在另一个用户尝试删除它时关联标签。

Having such a method (_db.IsValidToDelete(object)) will not guarantee you that it is safe to delete. Your application is a multi-user application. So one user may associate a tag when another user tries to delete it.

所以更好的选择是允许用户删除标签并捕获异常来检查是否是参照完整性违规。

So better alternative would be to allow user to delete the tag and catch the exception to examine whether it is a referential integrity violation.

这篇关于在ASP.NET MVC中删除前检查引用完整性违例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆