I'm sure someone has seen this: Cannot remove an entity that has not been attached. with LINQ

…衆ロ難τιáo~ 提交于 2020-03-25 03:35:40

问题


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

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


回答1:


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




回答2:


I came up with a solution! I queried the data context object to retrieve the object with same id as the one returned then deleted from same data context.

var delpatfile = db.PatientFiles.SingleOrDefault(p => p.Id == patfile.Id);
                 db.PatientFiles.DeleteOnSubmit(delpatfile);
                 db.SubmitChanges();

Since it was coming from same data context, it was already attached. I guess it might not be the only way to go about this so if anyone still has answers, feel free to post.

Thanks.



来源:https://stackoverflow.com/questions/11204491/im-sure-someone-has-seen-this-cannot-remove-an-entity-that-has-not-been-attach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!