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?
The DbContext. Remove method results in the entity's EntityState being set to Deleted .
DbContext. Remove Method (Microsoft.
To remove a table, simply remove the corresponding DbSet<MyClass> and any references to that class in other parts of your model and EF will add a DropTable to the migration automatically. If you are no longer using the class for non-Entity Framework purposes you can delete it.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With