How can I delete object with DbContext in c#?

.net c# entity-framework linq winforms

Question

This is how I delete:

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

I receive the following error when I press that remove button:

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

Due to the fact that there were two incidences ofContext class. So I did as follows:

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 I received the subsequent error:

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

How can I correct this and remove the object from the context database set?

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

Accepted Answer

To remove an object from context, you must first locate it. I have utilized a resource namedId . This isn't necessarily the case. There, the corresponding key property has been set by you.

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

To better comprehend the following error message, let's dig a little deeper:

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

Exactly whatObjectStateManager In accordance with 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.

Along with the aforementioned:

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

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

Popular Answer

Try replacing remove with delete and wrapping 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