Home > Software design >  Delete parent if no children in EF Core 7
Delete parent if no children in EF Core 7

Time:12-05

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);

CodePudding user response:

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.

  • Related