我确定有人已经看到了这一点:无法删除未附加的实体。与LINQ [英] I'm sure someone has seen this: Cannot remove an entity that has not been attached. with LINQ

查看:76
本文介绍了我确定有人已经看到了这一点:无法删除未附加的实体。与LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用LINQ的情况如下:
我有一种查询表并使用以下代码返回一条记录的方法

The scenario I am using LINQ is as follows: I have a method that queries a table and returns one record using the following code

private L2SQLData.PatientFile getpatfile(long id)
{
   var db = new HMSDataContext();
   var patfile = 
   (from f in db.PatientFiles.Where(f=> f.Id == id) select   f).FirstOrDefault() ;

   return patfile;
}

然后另一个代码调用上面的方法并获取返回的对象/记录。然后从同一表中将其删除,如下所示:

Then another code calls the method above and takes object/record that was returned. Then deletes it from the same table as follows:

L2SQLData.PatientFile patfile = getpatfile(long.Parse(id));

var db = new HMSDataContext();
db.PatientFiles.DeleteOnSubmit(patfile);
db.SubmitChanges();

在运行它时,VS2010会发出错误消息:无法删除未附加的实体。我究竟做错了什么?有人吗?

On running it, VS2010 screams with the error: Cannot remove an entity that has not been attached. What am I doing wrong? Anyone?

推荐答案

尝试 db.PatientFiles.Attach(patfile)还是尝试仅使用一个全局 HMSDataContext

Try db.PatientFiles.Attach(patfile) or try using only one globaly HMSDataContext

这篇关于我确定有人已经看到了这一点:无法删除未附加的实体。与LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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