Delete parent if no children in EF Core 7

Delete parent if no children in EF Core 7

Problem Description:

Using EF Core 7 and .NET 7 (but also in previous versions), it is possible to delete all children of a one-to-many relationship in a SQL server database by configuring the delete behavior of the parent entity in the OnModelCreating-method in the class deriving from the DbContext-class, like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Department>()
            .HasMany(d => d.Employees)
            .WithOne(e => e.Department)
            .OnDelete(DeleteBehavior.Cascade)
    }
}

But what if I want to delete the parent if all child entities are deleted?

I’ve tried mapping a reversed delete pattern from the one above (see below), but to no success.

    modelBuilder.Entity<Employee>()
        .HasOne(e => e.Department)
        .WithMany(d => d.Employees)
        .OnDelete(DeleteBehavior.Cascade);

Solution – 1

ORM engines are inspired from the relational database management systems. Removing a parent when last child is removed is not a standard operation on a relation change in the DB engines. So EFCore does not support it to. At the database level you can use triggers to achieve what you want.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject