Linq-to-sql "Unable to delete an object that was not attached"

I get a Cannot remove an entity that has not been attached. error message Cannot remove an entity that has not been attached. when trying to delete a record. I googled around and although there are many places to find a solution to fix this problem, the proposed fix does not allow me:

 using (MyDataContext TheDC = new MyDataContext()) { TheDC.MyTable.Attach(ARecord); //added this line but doesn't fix it. TheDC.MyTable.DeleteOnSubmit(ARecord); TheDC.SubmitChanges(); 

My bigger question is this: this problem ONLY affects delete requests or affects other kinds of requests, and I just haven't run into this problem yet. I wrote an update request and it seems to work without errors in this error.

Thanks.

+8
c # linq linq-to-sql
source share
2 answers

Please refer to this SO post: How to delete in linq in sql?

... about attaching if you already have a primary key. If you do not have a primary key, I always made a selection and then deleted, but when I make a selection, I try to keep the primary key for updates and deletes.

It will delete the primary key, but if you have it, just attach as I do below and call delete. I don’t miss the object needed by DLINQ, because I want to be able to change it if I want, so I pass another User object and just pulled PK out of the business class and put it in the DAO class.

 var db = new MeatRequestDataContext(); if (input.UserID > 0) { entity = new User() { UserID = input.UserID }; db.Users.Attach(entity); db.Users.DeleteOnSubmit(entity); } 
+11
source share

For me, the fix looked only for the database object.

 var db = new MeatRequestDataContext(); if (input.UserID > 0) { var existing = db.Users .Single(user => user.UserID == input.UserID); db.Users.DeleteOnSubmit(existing); } 

In my opinion, I could only delete what was already there, so I needed to first get the items in the database that I wanted to delete. This also works with collections and DeleteAllOnSubmit ().

+4
source share

All Articles