Reputation: 4836
I am trying to delete an entity using EF6.0 but I'm stuck in a situation and getting exception. Below is the code snippet where I'm running into exception
_context.Images.Remove(image)
I have a separate logic that gives me this entity. I'm getting below exception:
The object cannot be deleted because it was not found in the ObjectStateManager.
Upon googling I found out that since entity is fetched with separate context and getting deleted in separate context i'm getting this error. I don't want to fetch the entity again. I want to use the fetched entity itself but can't find a way to do so.
Upvotes: 1
Views: 361
Reputation: 12805
What you need to do is Attach() the entity to the context. This will then give your DbContext knowledge of the object. As long as your entity has a valid ID, you'll be fine.
Here is some pseudo-code to give you an idea of what you'll need to do.
using (var context = new MyDbContext())
{
// Make your context aware of the object.
context.Images.Attach(image);
// Now delete the object. It will change the internal
// state so that it will be deleted.
context.Images.Remove(image);
// Finally, save your changes
context.SaveChanges();
}
Upvotes: 2