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?
There’s no “Detach” method, but it is possible with serialization:
Be aware that it’s cumbersome to re-attach the object afterward. The
Attachtable method is finicky – you generally need aVersion(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
Customervianew Customer()will not create an attached entity. It only becomes attached after you invoke theInsertOnSubmitorAttachmethod 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 theDataContextitself or if you attach it using one of methods above.