Implementing Cascade Delete behavior in EF Core

The definition of Cascade Delete is if a record in the parent table is deleted, the corresponding records in the child table will automatically be deleted.

Now that we know what Cascade Delete is all about, let’s implement this behavior in EF Core where we will use Department and Employee tables. A Department can have one or more Employees. In other words, it’s a One to Many relationship. The idea is when we delete a record in the Department table, any references it has to the deptId key in the Employees table will also be deleted.

In the code that follows, the code loads records from the Department table and its corresponding Employees from the database. Notice the include method that is being used here. When SaveChanges is called, the cascade delete rules will be applied to the entities that are being tracked by the context.

Before Deletion:

CascadeDeleteBefore

private static void CascadeDelete()
        {
            using (var db = new DepartmentContext())
            {
                var depts = db.Departments.Include(e => e.Employees).First();
                db.Remove(depts);
                db.SaveChanges();
            }
        }

After Deletion:

CascadeDeleteAfterAs you can see DepID 8 which happened to be the first record in the Department table had two related Employees, namely, Rebecca D’Souza and Chris Wood. When the Department record with an Id of 8 was removed, it also deleted its corresponding Employees.

Since all Employees were tracked by the dbContext, the cascade behavior was applied before saving entries to the database. As a result, Entity Framework issued a DELETE statement for each of the matching entities.

About Obi Oberoi

I am Technology Aficionado who has a passion for learning, speaking, blogging and hanging out with geeks and like minded people!
This entry was posted in ORM. Bookmark the permalink.