linq-to-sql “Cannot remove an entity that has not

2019-06-15 19:50发布

I'm getting the error Cannot remove an entity that has not been attached. when I try to delete a record. I've googled around and although there's plenty of places to find the solution to fix this problem, the suggested fix doesn't get me further:

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: does this issue ONLY affect delete queries or does it affect other kinds of queries too and I just haven't bumped into this problem yet. I've written an update query and it seems to work without running into this error.

Thanks.

2条回答
叛逆
2楼-- · 2019-06-15 20:27

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

...about attaching, if you already have the primary key. If you don't have the primary key then I have always just done a fetch then a delete, but, whenever I do a fetch I tend to store the primary key for updates and deletes.

It will delete off of the primary key, but if you have that then just attach as I do below and call delete. I don't pass around the object needed by DLINQ as I want to be able to change it if I want, so I pass in a different User object and just pull the PK from the business class and put it into 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);
 }
查看更多
太酷不给撩
3楼-- · 2019-06-15 20:35

For me, the fix was just searching for the database object first.

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

    db.Users.DeleteOnSubmit(existing);
}

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

查看更多
登录 后发表回答