Charles
Charles

Reputation: 499

I'm sure someone has seen this: Cannot remove an entity that has not been attached. with 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();

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

Upvotes: 1

Views: 3719

Answers (2)

Yuri
Yuri

Reputation: 72

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

Upvotes: 2

Charles
Charles

Reputation: 499

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.

Upvotes: 2

Related Questions