Entity Framework Cascade Delete

With Entity Framework setting up a one to many relationships can present problems when you try to delete the parent entity. For example, you might have a User who has many Blog Posts (One user to many blog posts). If you try to delete the user you will be told you cannot because of the foreign key relationship.

What you can do with Entity Framework is use the RemoveRange function, the code below shows this being used.

private void DeleteUser()
{
    using (var db = new MyApplicationnContainer())
    {
        var user = (from u in db.Users
                    where u.Name == "Alan.Feekery"
                    select u).FirstOrDefault();

        db.BlogPosts.RemoveRange(user.Posts);

        db.Users.Remove(user);

        db.SaveChanges();
    }
}

So now when I delete a user, all the blog posts associated to this user will also be removed, if I didn’t do this I would be unable to delete the user from the database.

Source: Entity Framework on delete cascade

Advertisements

Published by

Alan Feekery

Developer, Gamer, Musician, Cyclist and big Motorsport fan... enjoys the odd cup of coffee :)

3 thoughts on “Entity Framework Cascade Delete”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s