简体   繁体   中英

Delete parent if no children in EF Core 7

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM