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

.net c# entity-framework

Question

I have this code which normally works:

db.myTable.DeleteObject(myCurrent);

And I got this error:

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

The same ingredients IS in the table in the database.

I tried this:

db.myTable.Attach(myCurrent);
db.myTable.DeleteObject(myCurrent);

And I got another error:

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

How to fix this?

1
20
4/11/2013 9:57:29 AM

Accepted Answer

The other answer didn't work, so here's how I fixed it.

Previously I had:

public void ok(myTable myCurrent)
{
    //delete entries from other tables in relationship with myTable
    db.myTables.DeleteObject(myCurrent);

}

I fixed it with this:

public void ok(int current_id)
{
    //delete entries from other tables in relationship with myTable
    var y = (from x in db.myTables where x.id == current_id select x).First();
    db.myTables.DeleteObject(y);

}
9
4/16/2013 8:13:02 AM

Popular Answer

The problem is you cannot delete (or remove) detached entities and cannot attach an entity twice. You need something like below.

var entry = db.Entry(myCurrent);
if (entry.State == EntityState.Detached)
    db.myTable.Attach(myCurrent);
db.myTable.Remove(myCurrent);


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