title: c# Entity Framework Remove an added object from the Data Context before SaveChanges
body: <p>I am trying to remove entities from the Context before SaveChanges is called.</p>
  
  <p>the entities are added like so</p>
  
  <pre><code>DbContext.Set&lt;T&gt;().Add(new T());
  </code></pre>
  
  <p>Originally I would remove single items by setting their state to EntityState.UnChanged where applicable in my overridden DbContext.SaveChanges() method.</p>
  
  <p>But where I have multiple entities that I do not want persisted, when the second entity has its state changed to UnChanged I get an error - "Saving or accepting changes failed because more than one entity has the same primary key value" - obviously they all have an ID of 0 because they haven't been saved yet.</p>
  
  <p>When I try </p>
  
  <pre><code>DbContext.Set&lt;T&gt;().Remove(entity);
  </code></pre>
  
  <p>it just doesn't remove the entity</p>
  
  <p>I know setting the EntityState to UnChanged was a bit of a hack I discovered years back, and now its come back to bite me!</p>
  
  <p>If any body can tell me how to remove an unsaved entity from the DbContext before saving I will be most grateful.</p>
  
  <p>Best Regards</p>
  
  <p>Lance</p>