Entity Framework How Do I Detach All Objects Of Specific Type From Datacontext?

asked9 years ago
last updated9 years ago
viewed10.3k times
Up Vote12Down Vote

Currently I am trying to implement code prior to my datacontext.savechanges() method that detaches all objects of a specific type from the data context so that they do not get inserted into the database. I know that you can call dbContext.Entry(entity).State = EntityState.Detached to detach a single entity, but is there a way to detach all objects of a specific type from the context?

Edit: I implemented what Mark C suggested and it compiles, but I get an invalid operation exception when I try to execute the code:

The entity type DbEntityEntry is not part of the model for the current context.

foreach (System.Data.Entity.Infrastructure.DbEntityEntry dbEntityEntry in this.dataContext.ChangeTracker.Entries<Customer>())
            {
                if (dbEntityEntry != null && dbEntityEntry.State != System.Data.Entity.EntityState.Modified && dbEntityEntry.State != System.Data.Entity.EntityState.Unchanged)
                {
                    dataContext.Entry(dbEntityEntry).State = System.Data.Entity.EntityState.Detached;
                }
            }

Edit #2: After looking at it more closely, I was making a mistake. It appears one needs to specify the entity on DBEntityEntry. With the following change it works:

foreach (System.Data.Entity.Infrastructure.DbEntityEntry dbEntityEntry in this.dataContext.ChangeTracker.Entries<Customer>())
        {
            if (dbEntityEntry.Entity != null && dbEntityEntry.State != System.Data.Entity.EntityState.Modified && dbEntityEntry.State != System.Data.Entity.EntityState.Unchanged)
            {
                dataContext.Entry(dbEntityEntry.Entity).State = System.Data.Entity.EntityState.Unchanged;
            }
        }

Thanks to Gert for recommending using EntityState.Unchanged instead of EntityState.Detached.