开发者

Checking for Referential Integrity Violation before deletion in 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.C开发者_JAVA百科ount == 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: 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.

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)?


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.


Btw. each call like tag.Stands.Count will load all related Stands from the database to your application so if you have a lot of relations and each contain a lot of entities this validation will be damn expensive and slow.

You can either use @Eranga's advice and catch exception or create stored procedure for tag deletion.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜