Search code examples
c#visual-studio-2008linq-to-sqldetach

LINQ to SQL: Create a dettached entity object


I have generated few classes using to LINQ to SQL

one of them being "Customer"

Now I want to create a Customer object that is disconnected.

i.e. I can create the object keep it in session and then attach it back only if I want to. Not automatically. Hence only if I attach it - it should affect my context's SubmitChange() otherwise not.

Is this possible?

Also can I add this detached object to a collection of attached objects without affecting SubmitChanges() or on add will the detached object become attached again?


Solution

  • There's no "Detach" method, but it is possible with serialization:

    Customer customerCopy;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, customer);
        ms.Position = 0;
        customerCopy = (Customer)bf.Deserialize(ms);
    }
    

    Be aware that it's cumbersome to re-attach the object afterward. The Attach table method is finicky - you generally need a Version (timestamp type) column on the entity in order for it to work.

    Note - I just reread your question and it sounds almost as though you simply want to construct the object. If so, constructing a new Customer via new Customer() will not create an attached entity. It only becomes attached after you invoke the InsertOnSubmit or Attach method on the table.

    Also, you can freely add detached entities to a List<Customer> (or similar) containing attached entities - Linq to SQL does not care about this, an entity only becomes attached if it is dispensed by the DataContext itself or if you attach it using one of methods above.