Wednesday 18 September 2013

Cascading Deletions in Entity Framework

Model_thumb6Imagine that there is the model shown on the picture. You want to delete an entity of type “Specification”. There is an option called “Cascading” that can be defined under the corresponding relation between two database entries. When Cascading is on, all you need to do is simply delete the parent object. Cascading takes care of the rest, which means that it automatically clears out all related child objects.
The code that is needed comes below:








 public static void Delete(int specificationId)  
 {  
    var db = new WebEntities(); // Your entity framework context object  
    var spec = db.Specifications.Where(item => item.Id == specificationId).FirstOrDefault();  
    if (spec == null) return;  
      db.Specifications.Remove(spec);  
    db.SaveChanges();  
 }  

Untitled_thumb2But how can you turn on Cascading? This is relatively simple. In SQL Management Studio find the table Specification, right click on the name and select “Design”. You should see an Excel-like table which you can use to edit the schema for the table structure. Right click on the vertical bar of the table and select Relationships. Then select the 1-n relation between Specifications and SpecificationHeaders and edit the DELETE rule und INSERT And UPDATE Specification. Select the Cascade option as shown in the picture below.





Capture_thumb2

The same thing needs to be done for the relation between SpecificationHeader and SpecificationItem, but I hope you can manage that on your own.

Capture2_thumbThere is a last step left. Go to your edmx model browser in Visual Studio and update your model from the database. Then select the arrow that describes the relation, go to properties and advise Entity Framework to use cascading on Deletion. You see, Entity Framework does not get this info simply by updating the model from the database. Check the picture to see how this is done. The same applies to all cascading relationships.

Save all changes to your Entity Model and normally you should be able to use cascading deletions only by applying the Remove method to the parent Specification object.

No comments:

Post a Comment