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

c#, entity-framework

Solution

You could write something like

foreach (DbEntityEntry dbEntityEntry in this.ChangeTracker.Entries())
            {
                if (dbEntityEntry.Entity != null)
                {
                  // Here you can look at typeof and the EntityState
                }
            }

Thanks for KeithS for pointing out that you can also use the overload for `ChangeTracker.Entries()` for using specific Entity types.

`this.ChangeTracker.Entries<SomeEntityEntity>()`

Problem

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.

Original source