LINQ到SQL"无法删除尚未连接&QUOT的实体; [英] linq-to-sql "Cannot remove an entity that has not been attached"

查看:264
本文介绍了LINQ到SQL"无法删除尚未连接&QUOT的实体;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到的误差无法删除尚未连接的实体。当我尝试删除记录。我周围的一派,虽然有很多的地方找到解决方案来解决这个问题,建议的修复并没有得到进一步的我:

 使用(MyDataContext TheDC =新MyDataContext())
{
TheDC.MyTable.Attach(的arecord); //加入这一行,但不解决它。
TheDC.MyTable.DeleteOnSubmit(的arecord);
TheDC.SubmitChanges();



我的更大的问题是:是否这个问题只影响删除查询或不会影响其他类型的查询也和我只是还没有碰到这个问题呢。我写了一个更新查询,它似乎没有运行到这个错误的工作。



感谢。


解决方案

请参阅本SO帖子:如何在LINQ to删除为sql?




...有关如何安装,如果你已经有主键。如果没有主键,然后我一直刚刚做了提取,然后删除,但是,每当我做一个获取我倾向于存储主键的更新和删除。



它会删除掉的主键的,但如果你有那么只是附加为我做以下,并呼吁删除。我没有通过围绕由DLINQ需要的,因为我希望能够改变它,如果我想的对象,所以我通过在一个不同的用户对象,并从业务类只是拉的PK,并把它放入DAO类。

 变种DB =新MeatRequestDataContext(); 
如果(input.UserID大于0)
{
实体=新用户()
{
=用户ID input.UserID
};
db.Users.Attach(实体);
db.Users.DeleteOnSubmit(实体);
}



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.

解决方案

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);
 }

这篇关于LINQ到SQL"无法删除尚未连接&QUOT的实体;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆