O'Reilly logo

Code-First Development with Entity Framework by Sergey Barskiy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Deleting data from the database

Interestingly enough, there is a lot of similarity in the approaches we used for updates and deletions. We can use a query to find data and then mark it for deletion by using the Remove method of DbSet. This approach actually has the same drawbacks as it does with the update, resulting in a select query in addition to the delete query. Nonetheless, let's take a look at how it is done:

using (var context = new Context())
{
    var toDelete = context.People.Find(personId);
    toDelete.Phones.ToList().ForEach(phone => context.Phones.Remove(phone));
    context.People.Remove(toDelete);
    context.SaveChanges();
}

This code deletes each child entity, phone in our case, and then deletes the root entity. You would have to know the primary ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required