Efcore: Removing entities

Created on 1 Oct 2019  路  4Comments  路  Source: dotnet/efcore

In EF 2.2, I created a Clear extension that would clear entities out of the ChangeTracker. This was mostly required for unit tests that couldn't control the scope of the DbContext they were given.

The method was simple:

        public static void Clear(this DbContext context)
        {
            var entries = context.ChangeTracker.Entries().ToList();
            //var cascadeTiming = context.ChangeTracker.CascadeDeleteTiming;
            //context.ChangeTracker.CascadeDeleteTiming = CascadeTiming.Never;
            //var orphansTiming = context.ChangeTracker.DeleteOrphansTiming;
            //context.ChangeTracker.DeleteOrphansTiming = CascadeTiming.Never;

            foreach (var entry in entries)
            {
                entry.State = EntityState.Detached;
            }

            //context.ChangeTracker.CascadeDeleteTiming = cascadeTiming;
            //context.ChangeTracker.DeleteOrphansTiming = orphansTiming;
        }

However, in 3.0 this gives me errors about not being able to cascading deletes. I forget the exact exception now. You can see I have a few commented lines where I was trying to disable that new feature that I believe triggered the exceptions.

So the question is: is there a supported way to "clear" the tracked entities?

closed-question customer-reported

Most helpful comment

@WinniX if what you want is to clear the change tracker, then in 5.0 there's the new ChangerTracker.Clear which does this for you efficiently and out-of-the-box.

All 4 comments

@joshmouch The issue you are experiencing is https://github.com/aspnet/EntityFrameworkCore/issues/17784

The recommended way to reset a context is to create a new instance, but you can also do this:
C# var configuration = ((IDbContextPoolable)context).SnapshotConfiguration(); ((IResettableService)context).ResetState(); ((IDbContextPoolable)context).Resurrect(configuration);

@AndriySvyryd I am sorry for re-opening this, but my question seems to be relevant within EF Core 5.0 release. There is no Resurrect() method in v5.0, does it mean it's enough to do just this?

((IDbContextPoolable)context).SnapshotConfiguration();
((IResettableService)context).ResetState();

@WinniX if what you want is to clear the change tracker, then in 5.0 there's the new ChangerTracker.Clear which does this for you efficiently and out-of-the-box.

@roji I am sorry for bothering you again on this, but I have another question on this topic. In EF Core 3.1 we've been using:

var configuration = ((IDbContextPoolable)context).SnapshotConfiguration();
((IResettableService)context).ResetState();
((IDbContextPoolable)context).Resurrect(configuration);

Exactly what @AndriySvyryd had suggested above. The question is how to achieve the same within EF Core 5?

Thank you very much for your assistance!

Was this page helpful?
0 / 5 - 0 ratings