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 key value for the entity you want to delete. The preceding code assumes that you have this value in the personId
variable. In the case of a web application, this value will be submitted to the method that handles deletion. Alternatively...