C# Entity Framework – Clear Context

Put the following code in the partial class of your entity context:

    public partial class MyEntities
    {

        public IEnumerable GetAllObjectStateEntries()
        {
            return ObjectStateManager.GetObjectStateEntries(EntityState.Added |
                                                        EntityState.Deleted |
                                                        EntityState.Modified |
                                                        EntityState.Unchanged);
        }

        public void ClearEntities()
        {
            foreach (var objectStateEntry in GetAllObjectStateEntries())
            {
                Detach(objectStateEntry.Entity);
            }
        }
    }

If you want to clear the context you just call the ClearEntities() method on the reference to the context

But be aware that this code does set all foreign key references to null in all entities that have been retrieved from the context before the method was called. You should not use any entities of the context anymore when you call this code.

Leave a comment

Your email address will not be published. Required fields are marked *