Raven231
Raven231

Reputation: 13

Exception : Cannot remove an entity that has not been attached

I'm getting the error

"Cannot remove an entity that has not been attached."

for the above code when I try to delete a record. I have searched a lot for the same but of no use.

public ActionResult Delete(int id) {
        tbl_user_master emp = db.tbl_user_masters.Where(val => val.UserId == id).Select(val => new tbl_user_master()
            ).SingleOrDefault();

        db.tbl_user_masters.DeleteOnSubmit(emp);
        db.SubmitChanges();

        return RedirectToAction("Index", "User");
    }

i expect the preferred row to be deleted rather than bringing me again to the code every time.

Upvotes: 0

Views: 292

Answers (3)

Raven231
Raven231

Reputation: 13

tbl_user_master emp = db.tbl_user_masters.Where(val => val.UserId == id).Select(val => val 
            ).SingleOrDefault();

This helped me to solve the code

Thank you

Upvotes: 1

trailmax
trailmax

Reputation: 35106

You need to get the object like this

tbl_user_master emp = db.tbl_user_masters.SingleOrDefault(val => val.UserId == id);

You were getting a new tbl_user_masters object from select and that object was not something EF tracks.

Upvotes: 0

Shahzad Khan
Shahzad Khan

Reputation: 530

How to use and apply the DeleteOnSubmit to your application with entity framework.

Upvotes: 0

Related Questions