How can I delete object with DbContext in c#?
Solution 1
You have first to 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 to 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.
Solution 2
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();
}
Comments
-
Jahongir Rahmonov almost 2 years
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?
-
Jahongir Rahmonov about 9 yearsLove this :) Thank you sir !
-
Wes H about 6 yearsI would love to see this updated to include the definition of db and item.