DenaliHardtail
DenaliHardtail

Reputation: 28326

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?

Upvotes: 2

Views: 2005

Answers (3)

JackD
JackD

Reputation: 597

You have two ways of cascade deleting implementation:

  1. Set up it on the database layer (triggers or relationships)
  2. Try to use extension methods. You can define delete logic for current table and call methods for related table updating.

Upvotes: 0

rino.batin
rino.batin

Reputation: 419

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();
        }

Upvotes: 0

morganpdx
morganpdx

Reputation: 1876

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.

Upvotes: 4

Related Questions