How do I perform cascading deletes with EF4?
On a previous project we had EF4 performing cascading deletes (Delete a parent record and the 开发者_运维百科child records are deleted, too). On this project (different company), EF4 is not performing cascading deletes. What do I need to do to make EF4 perform a cascading delete?
Using just EF4's cascading delete is not enough; you should set up cascading deletes on your database as well, in case not all children are loaded into the object context. That being said, the cascade delete properties are set on the assocation. Go to the model browser, select an assocation and view properties.
I am on the same boat. I only have cascade on delete in EDM/EF4 and not (yet) in the database. Try this...
In the relationship, set the OnDelete of parent's end (1 multiplicity) to Cascade . Then in your code load all children before saving the changes (deletion).
var parent = context.Parents.SingleOrDefault(p => p.Id == parentId);
parent.Children.Load();
if (parent != null)
{
context.Parent.DeleteObject(parent);
context.SaveChanges();
}
You have two ways of cascade deleting implementation:
- Set up it on the database layer (triggers or relationships)
- Try to use extension methods. You can define delete logic for current table and call methods for related table updating.
精彩评论