This is a migrated thread and some comments may be shown as answers.

Delete fails with An object with a temporary EntityKey value cannot be attached to an object context

4 Answers 122 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Shawn
Top achievements
Rank 2
Shawn asked on 30 Jun 2012, 01:44 PM
I'm using Ajax binding, and my Destroy method looks like this:
[HttpPost]
public ActionResult AjaxDelete([DataSourceRequest]DataSourceRequest request, tbl_app_Customer customerToDelete) {
if (customerToDelete != null) {
db.tbl_app_Customer.Attach(customerToDelete);
                db.ObjectStateManager.ChangeObjectState(customerToDelete, EntityState.Deleted);
                db.SaveChanges();
        }
        return Json(ModelState.ToDataSourceResult());
}
However this code fails with the error:
An object with a temporary EntityKey value cannot be attached to an object context

Any idea why this is? What am I doing wrong?

4 Answers, 1 is accepted

Sort by
0
Shawn
Top achievements
Rank 2
answered on 15 Jul 2012, 08:57 AM
Please somebody from Telerik help
0
Vitali
Top achievements
Rank 1
answered on 19 Jul 2012, 08:54 PM
Hey Shawn, I am was wondering how to configure my destroy action so that it accepts the model I want to destroy
0
Mark
Top achievements
Rank 1
answered on 20 Jul 2012, 10:20 AM
Hello? Has anyone found a solution to this? How come the Kendo guys are ignoring this? have exactly the same problem and have been at it for days now, yet I am still stuck. I aso get the same error when I attempt t update.  Please someone who has experience with this, share your knowledge with us? Thank you!
0
Victor
Top achievements
Rank 1
answered on 31 Jul 2012, 10:07 PM
I suppose you are using entity framwork? We are too, maybe I can help some... We always take the Id as the argument, not the full record. Then get the entity from the DB and then delete it (similair to updates). Since http is state-less I dont think you can assume that the the object in the db corresponds to the object the client sent. So, your code would be something like:

[HttpPost]
public ActionResult AjaxDelete([DataSourceRequest]DataSourceRequest request, Guid id) {
        //id could of course be an int or something else
        try {
            var customer = customerObjectSet.Single(c => c.Id == id);
            //or how you usually get your object from the db
            customerObjectSet.Delete(customer);
            db.SaveChanges();
            //Probably return success message or something
            return Json(ModelState.ToDataSourceResult());
        }
        catch {
            throw new SomethingTerribleWentWrongException();
            //Or whatever error handling
        }
}

/Victor
Tags
Grid
Asked by
Shawn
Top achievements
Rank 2
Answers by
Shawn
Top achievements
Rank 2
Vitali
Top achievements
Rank 1
Mark
Top achievements
Rank 1
Victor
Top achievements
Rank 1
Share this question
or