问题
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