Fabien Dezautez
Fabien Dezautez

Reputation: 129

One to many relation : child is flagged Modified instead Deleted

I have some troubles using One to Many relationships with EntityFramework Core. When I delete a child object in the List property on the parent, this Child object is flagged as Modified by the ChangeTracker (and not Deleted). However, when I call SaveChanges on the context, this entity is well Deleted.

Of course, I could force the flag of the entity to Deleted but, I would prefer another solution because I'm using AutoMapper to update my entities. and I don't want to mix the AutoMapper mapping process and EntityFramework Context.

var parent = new Parent();

var child = new Child();
parent.Childs.Add(child);
await context.SaveChangesAsync();

// removing the first child
parent.Childs.RemoveAt(0);  

// fails (Expected Deleted, got Modified)
Assert.Equal(EntityState.Deleted, context.Entry(child).State); 

Upvotes: 1

Views: 407

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205569

The best explanation of this behavior is contained inside one of the expected breaking changes in EF Core 3.0 - Cascade deletions now happen immediately by default:

Old behavior

Before 3.0, EF Core applied cascading actions (deleting dependent entities when a required principal is deleted or when the relationship to a required principal is severed) did not happen until SaveChanges was called.

New behavior

Starting with 3.0, EF Core applies cascading actions as soon as the triggering condition is detected. For example, calling context.Remove() to delete a principal entity will result in all tracked related required dependents also being set to Deleted immediately.

Why

This change was made to improve the experience for data binding and auditing scenarios where it is important to understand which entities will be deleted before SaveChanges is called.

The first section explains the current behavior and the last section explains why they are changing it - to help usage scenarios like yours.

With that being said, you should either apply the cascade option manually, or wait for EF Core 3.0 if you can afford that.

Upvotes: 1

Related Questions