How can I delete object with DbContext in c#?

.net c# entity-framework linq winforms

Question

I have this delete method:

private void btnDeleteOrderLine_Click(object sender, EventArgs e)
{
    OrderLine orderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;
    db.OrderLines.Remove(orderLine);
    db.SaveChanges();
    refreshGrid();
}

when I click that delete button, I get this error:

The object cannot be deleted because it was not found in the ObjectStateManager.

I found out that it is because there were two instances of Context class. So, I tried this:

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();
}

then this gave me the following error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

How can I fix this and delete an object from Context DbSet?

1
4
5/3/2015 7:36:54 PM

Accepted Answer

You have first find the item from the context and then remove it. I have used a property called Id. This is not might be the case. You have set there the corresponding key property.

var selectedOrderLine = (OrderLine)dgvOrderLine.SelectedRows[0].DataBoundItem;

// Here using the context class we try to find if there is the 
// selected item at all 
var orderLine = db.OrderLines.SingleOrDefault(item=>item.Id == selectedOrderLine.Id);

if(orderLine!=null)
{
    // The items exists. So we remove it and calling 
    // the db.SaveChanges this will be removed from the database.
    db.OrderLines.Remove(orderLine);
    db.SaveChanges();
    refreshGrid();
}

Now let's go a bit deeper, in order we understand the following error message:

The object cannot be deleted because it was not found in the ObjectStateManager.

What is the ObjectStateManager class? Accoding to MSDN:

ObjectStateManager tracks query results, and provides logic to merge multiple overlapping query results. It also performs in-memory change tracking when a user inserts, deletes, or modifies objects, and provides the change set for updates. This change set is used by the change processor to persist modifications.

In addition to the above:

This class is typically used by ObjectContext and not directly in applications.

9
5/3/2015 7:29:31 PM

Popular Answer

Try using delete instead of remove and wrap it in using

using (YourContext db = new YourContext())
 {
            db.OrderLines.Attach(orderLine);  // added this part
            db.OrderLines.DeleteObject(orderLine);
            db.SaveChanges();   
  }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow