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();
}
But 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.
The same thing needs to be done for the relation between SpecificationHeader and SpecificationItem, but I hope you can manage that on your own.
There 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