Wednesday 18 September 2013

Cascading Deletions Through Code

ModelLet´s say that you do not want to use the database way, that you have a good reason to implement cascading deletions in your code only (maybe because you have no access to the database). In this case, you need to manually remove the related entities of the object under deletion.
Let´s take the Specifications´model. The predefined relations are shown in the picture, yet, cascading has not been enabled for deletions in the SQL server for the corresponding relations. Then, you need to make sure that, when removing a specification, all its SpecificationHeaders have been removed first. Of course, each and every SpecificationHeader must have been cleared off its SpecificationItems prior to its own removal.

Here is some code to do that:



 public static void Delete(int specificationId)  
 {  
   DeleteHeaders(specificationId);  
   var db = new WebEntities();  
   var spec = db.Specifications.Where(item => item.Id == specificationId).FirstOrDefault();  
   if (spec == null) return;  
   db.Specifications.Remove(spec);  
   db.SaveChanges();  
 }  
 private static void DeleteHeaders(int specId)  
 {  
   var db = new WebEntities();  
   var spec = db.Specifications.Where(item => item.Id == specId).FirstOrDefault();  
   if (spec == null) return;  
   foreach (var header in spec.SpecificationHeaders)  
      DeleteItems(header.Id);  
   spec.SpecificationHeaders.ToList().ForEach(r => db.SpecificationHeaders.Remove(r));  
   db.SaveChanges();  
 }  
 private static void DeleteItems(int headerId)  
 {  
   var db = new WebEntities();  
   var header = db.SpecificationHeaders.Where(item => item.Id == headerId).FirstOrDefault();  
   if (header == null) return;  
   header.SpecificationItems.ToList().ForEach(r => db.SpecificationItems.Remove(r));  
   db.SaveChanges();  
 }  

The three methods take care of the cascading deletion of child items in-code. I must comment here that this solution is way slower than using cascading On when defining the database schema. However, this should get you going if you have no influence on that part.

Cheers.

No comments:

Post a Comment