LINQ - Delete Issue in attach method

Ajit_Kr
Ajit_Kr used Ask the Experts™
on
I am using LINQ. when I want to delete the record using

using (dbDataContext dc = new dbDataContext(ConnectionString))
  {
     dc.Contractors.Attach(_Client);
      DeleteClient(dc, _Client);
      dc.SubmitChanges();
  }

it show me error on line
dc.Contractors.Attach(_Client);
and error message is

An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from another DataContext. This is not supported.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2009

Commented:
Fernando SotoRetired
Distinguished Expert 2017

Commented:
Hi Ajit_Kr;

1. Where is the Contractors _Client record coming from?
2. Is it being created in one data context and trying to add it to another data context with in the same program?
3. Or is it a record created on a server and received on a client machine?

If you are option 1 above then change your code to this:

using (dbDataContext dc = new dbDataContext(ConnectionString))
{
    Contractors client = (from c in dc.Contractors
                          where c.Equals(_Client)
                          select c).FirstOrDefault();

    dc.Contractors.DeleteOnSubmit(client);
    dc.SubmitChanges();
}

Fernando
Lead Software Engineer
Commented:
The only thing you need for deleting items in Linq To Sql, is the ID (primary key). if you have this, you simply create the following:


using (dbDataContext dc = new dbDataContext(ConnectionString))
{
    Contractors c = new Contractors
{
 ID = ToBeDeletedID
}


    dc.Contractors.DeleteOnSubmit(c);
    dc.SubmitChanges();
}

As you can see, you don't need to have the whole item to delete one in Linq To Sql just the ID, unfortunatly, this is not possible in Linq To Entities (in EF you need to have the whole object)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial