Share via

Turning off cascade deletes

David Thielen 3,226 Reputation points
2023-03-19T18:37:30.1933333+00:00

I have a case where I need to turn off cascading deletes (two different models are both wanting to cascade delete and so one needs to be turned off). I think I have this right but I saw numerous different answers all over the place and so want to confirm.

public class Signup
{
    public required User User { get; set; }

    // lots of other properties
}

public class User
{
    public required ICollection<Signup> Signups { get; set; }

    // lots of other properties
}

public class SignupConfiguration : IEntityTypeConfiguration<Signup>
{
    /// <inheritdoc />
    public void Configure(EntityTypeBuilder<Signup> builder)
    {
        builder.HasOne(s => s.User).WithMany(u => u.Signups).OnDelete(DeleteBehavior.NoAction);
    }
}

Is this the correct way to tell EF that when deleting a User object, it should not cascade its child Signup objects? This works (I think). But I want to make sure this is the correct way to do this.

Also, it seems weird to me that saying this starts with the child Signup class instead of the parent User class.

Developer technologies | .NET | Entity Framework Core
0 comments No comments

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,316 Reputation points
    2023-03-20T10:23:37.8866667+00:00

    @David Thielen, Welcome to Microsoft Q&A,

    Is this the correct way to tell EF that when deleting a User object, it should not cascade its child Signup objects?

    Based on my test and research, it seems that EF Core does not allow you to do it.

    Please refer to the Microsoft Learning Fields about NoAction , which has the following sentence:

    If a property cannot be set to null because it is not a nullable type, then an exception will be thrown when SaveChanges() is called.

    Also, based on my test, it indeed throws the exception that does not allow you to delete User objects and Signup objects when I delete a User Object.

    If you just want to delete child objects, I recommend that you could delete the foreign key in database and then you could delete the User object and not delete child Signup objects

    Based on my test, it only deleted child objects and did not delete the parent objects.

    Hope my explanations could help you.

    Best Regards,

    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    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' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.