How to delete an object using DbContext in C #?

I have this removal 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 the delete button, I get this error:

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

I found out that this is because there were two instances of the 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 it gave me the following error:

An entity object cannot reference multiple instances of IEntityChangeTracker .

How can I fix this and remove the object from the Context DbSet?

+4
source share
2 answers

You will first find the item from the context, and then remove it. I used a property called Id . This is not true. You have set 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 release a little deeper to understand the following error message:

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

What is an ObjectStateManager class? MSDN negotiation :

ObjectStateManager tracks query results and provides logic for combining multiple overlapping query results. It also performs a change in memory tracking when a user inserts, deletes or modifies objects and provides a set of changes for updates . This set of changes is used to modify the processor to save changes.

In addition to the above:

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

+7
source

Try using delete instead of deleting and wrap it with

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

All Articles