TrackableEntities / TrackableEntities.Core

Change-tracking across service boundaries with .NET Core.
MIT License
74 stars 13 forks source link

AcceptChanges doesn't remove deleted items from collection #26

Closed brmza closed 3 years ago

brmza commented 5 years ago

I have an API controller that saves a list containing trackable entities.

this.context.ApplyChanges(list);
this.context.SaveChanges();
this.context.AcceptChanges(list);

Marking an entity as deleted correctly deletes the item from the database, however I would expect AcceptChanges to remove the item from the list?

tonysneed commented 5 years ago

I can't remember if this was intentional. Let me investigate further.

tonysneed commented 5 years ago

Calling SaveChanges removes deleted items from the list, so there is no need for AcceptChanges to do so. Hope this answers your question. Please feel free to re-open if needed.

brmza commented 5 years ago

EF does remove deleted items from child collections of entities it is tracking, but the parent items remain in the original list passed to Apply / AcceptChanges.

We have created a DBContextBase class with the following method which solves the problem.

public void AcceptChanges<TEntity>(List<TEntity> items)
       where TEntity : ITrackable
     {       
       // remove the deleted items from the original list
       foreach (var item in items.Where(item => item.TrackingState == TrackingState.Deleted).ToList())
       {
         items.Remove(item);
       }
       // let trackable entities do it's thing
       TrackableEntities.EF.Core.DbContextExtensions.AcceptChanges(this, items.Cast<ITrackable>());
     }
tonysneed commented 5 years ago

I understand now. It’s the top level objects that need to be removed. I think you have a good solution. If there are others interested in this solution it may be worth adding an overload to AcceptChanges for removing deleted items from the top level.

tonysneed commented 3 years ago

Closing this, as there is a workaround.