Home > Software design >  EF Core 6 Upgrade - Deleting Child Object Also Deletes Parent
EF Core 6 Upgrade - Deleting Child Object Also Deletes Parent

Time:03-11

I had an EF Core 2.2 project which I upgraded to EF Core 6. There is a situation where the user uploads a new set of values for an entity tracked by EF.

The code uses SetState to mark the old entity and its child entities as deleted and then sets the value to be the new object.

  • In EF Core 2.2 this worked.
  • Now in EF Core 6 when SaveChanges is called, the parent ConfigurationSettings entity is being deleted.
  • The parent object is not having its state set to deleted anywhere.
public void UpdateUserPreferences(UserPreferences newUserPreferences)
{
    var selectedUserConfig = this.database.ConfigurationSettings
        .Include(s => s.UserPreferences)
        .ThenInclude(sc => sc.UserPreference)
        .First(x => x.UserId == 1234);

    selectedUserConfig.UserPreferences.UserPreference
        .ToList()
        .ForEach(up => this.database.SetState(up, EntityState.Deleted);

    this.database.SetState(selectedUserConfig.UserPreferences, EntityState.Deleted);

    selectedUserConfig.UserPreferences = newUserPreferences;

    this.database.SaveChanges();
}

After the SaveChanges is called, a new UserPreferences entity is saved with the updated UserPreference child entities which is what we want. However the parent ConfigurationSettings entity is being deleted.

The database snapshot is configured with CascadeDelete

    modelBuilder.Entity("ConfigurationSettings", c =>
    {
        c.HasOne("UserPreferences", "UserPreferences")
            .WithMany()
            .HasForeignKey("UserPreferencesId")
            .OnDelete(DeleteBehavior.Cascade)
            .IsRequired()
            .HasConstraintName( "FK_dbo.ConfigurationSettings.UserPreferences_userPreferencesId" );
    }

What I want to be happening is that the existing ConfigurationSettings entity is not deleted and its UserPreferencesId is updated to the newly saved UpdatedPreferences entity.

There are no errors being thrown.

CodePudding user response:

I Misread the post and wrote a wrong answer, sorry

CodePudding user response:

In EF core 6 to turn off Cascade Deleting in you context in OnModelCreating method you have to put WillCascadeOnDelete like this example on false

modelBuilder.Entity<Student>()
            .HasOptional<Standard>(s => s.Standard)
            .WithMany()
            .WillCascadeOnDelete(false);
  • Related