Can Entity Framework cascade deletes of 1:many for same record types?

David Thielen 3,211 Reputation points
2023-07-06T22:14:17.2066667+00:00

I have the following model:

public class Organization
{
    public int Id { get; private set; }
    public Organization? Parent { get; set; }
    public ICollection<Organization>? Children { get; private set; }
}

Now I know, but obviously the database does not, that there will be no cycles in this parent-child set of collections. (An organization is a Country, State, or County.)

As I understand it, SQL Server (my underlying repository) sees the possibility of cycles and throws an exception if asked to perform a cascading delete. Is this correct?

In which case, is my best bet to do:

public class OrganizationConfiguration : IEntityTypeConfiguration<Organization>
{
    /// <inheritdoc />
    public void Configure(EntityTypeBuilder<Organization> builder)
    {
        builder.HasMany(x => x.Children).WithOne(x => x.Parent).OnDelete(DeleteBehavior.ClientSetNull);
    }
}

And then overload my DbContext.SaveChangesAsync and in that, walk children, grandchildren, etc. when an Organization is deleted and delete this (grand)children?

??? - thanks - dave

Developer technologies .NET Entity Framework Core
{count} votes

1 answer

Sort by: Most helpful
  1. Wenbin Geng 741 Reputation points Microsoft External Staff
    2023-07-11T13:30:47.0133333+00:00

    Hi @David Thielen , Welcome to Microsoft Q&A.

    After testing, I added five sets of data to the table, and the deletion was successful through the following code.

                using(var context = new MyDbContext())
                {
                    var parentOrganization = await context.organization.Include(x => x.Children).OrderBy(x => x.Id).FirstAsync();
    
                    // Remove parent reference from child organizations
                    foreach (var child in parentOrganization.Children)
                    {
                        child.Parent = null;
                    }
    
                    context.Remove(parentOrganization);
                    context.SaveChanges();
                }
                
    
    
    

    User's image

    User's image

    Best Regards,

    Wenbin


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.  


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.