title: How can I delete object with DbContext in c#?
body: <p>I have this delete method:</p>
  
  <pre><code>private void btnDeleteOrderLine_Click(object sender, EventArgs e)
  {
      OrderLine orderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;
      db.OrderLines.Remove(orderLine);
      db.SaveChanges();
      refreshGrid();
  }
  </code></pre>
  
  <p>when I click that delete button, I get this error:</p>
  
  <blockquote>
    <p>The object cannot be deleted because it was not found in the
    <code>ObjectStateManager</code>.</p>
  </blockquote>
  
  <p>I found out that it is because there were two instances of <code>Context</code> class. So, I tried this:</p>
  
  <pre><code>private void btnDeleteOrderLine_Click(object sender, EventArgs e)
  {
      OrderLine orderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;
      db.OrderLines.Attach(orderLine);  // added this part
      db.OrderLines.Remove(orderLine);
      db.SaveChanges();
      refreshGrid();
  }
  </code></pre>
  
  <p>then this gave me the following error:</p>
  
  <blockquote>
    <p>An entity object cannot be referenced by multiple instances of
    <code>IEntityChangeTracker</code>.</p>
  </blockquote>
  
  <p>How can I fix this and delete an object from Context DbSet?</p>