title: Entity Framework How Do I Detach All Objects Of Specific Type From Datacontext?
body: <p>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 <code>dbContext.Entry(entity).State = EntityState.Detached</code> to detach a single entity, but is there a way to detach all objects of a specific type from the context? </p>
  
  <p>Edit: I implemented what Mark C suggested and it compiles, but I get an invalid operation exception when I try to execute the code:</p>
  
  <blockquote>
    <p>The entity type DbEntityEntry is not part of the model for the current
    context.</p>
  </blockquote>
  
  <pre><code>   foreach (System.Data.Entity.Infrastructure.DbEntityEntry dbEntityEntry in this.dataContext.ChangeTracker.Entries&lt;Customer&gt;())
              {
                  if (dbEntityEntry != null &amp;&amp; dbEntityEntry.State != System.Data.Entity.EntityState.Modified &amp;&amp; dbEntityEntry.State != System.Data.Entity.EntityState.Unchanged)
                  {
                      dataContext.Entry(dbEntityEntry).State = System.Data.Entity.EntityState.Detached;
                  }
              }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>        foreach (System.Data.Entity.Infrastructure.DbEntityEntry dbEntityEntry in this.dataContext.ChangeTracker.Entries&lt;Customer&gt;())
          {
              if (dbEntityEntry.Entity != null &amp;&amp; dbEntityEntry.State != System.Data.Entity.EntityState.Modified &amp;&amp; dbEntityEntry.State != System.Data.Entity.EntityState.Unchanged)
              {
                  dataContext.Entry(dbEntityEntry.Entity).State = System.Data.Entity.EntityState.Unchanged;
              }
          }
  </code></pre>
  
  <p>Thanks to Gert for recommending using EntityState.Unchanged instead of EntityState.Detached.    </p>