I get an error when trying to delete a record:
InvalidOperationException – The object cannot be deleted because it was not found in the ObjectStateManager.
public ActionResult Delete(CustomerModel customer)
{
db.Customer.Remove(customer);
db.SaveChanges();
return View();
}
Update: I checked in the bebugger, customer is completely empty..And therefore the database isn’t able to delete that specific record.
Any ideas why?
Your customer object was not loaded into the DbContext called db (I’m assuming it’s a DbContext… not entirely clear from your code).
With Entity Framework, the DbContext you are using has to be aware of an object it is acting on. It looks like you created customer in some manner other than by loading it into db.
You can add it to the DbContext like this:
Then, proceed to remove it and save your changes.
For more details see
http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx
Specifically for your case the paragraph Attaching an existing entity to the context
Update (based on your update)
How did you create customer in the first place? Without that detail, it’s just guesswork to understand why it’s completely empty.