C# – Linq2Sql: Manage DataContext

asp.netclinq-to-sql

In the following code doesn't work as

public void Foo()
{
   CompanyDataContext db = new CompanyDataContext();
   Client client = (select c from db.Clients ....).Single();
   Bar(client);
}

public void Bar(Client client)
{
   CompanyDataContext db = new CompanyDataContext();
   db.Client.Attach(client);
   client.SomeValue = "foo";
   db.SubmitChanges();
}

This doens't work, I get error msg. "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."

How do you work with DataContexts throughout an application so you don't need to pass around a reference?

What

Best Answer

They really mean it with 'This is not supported.'. Attaching to an object fetched from another data context is not implemented.

There are a number of workarounds to the problem, the recommended way is by serializing objects, however this is not easy nor a clean approach.

The most simple approach I found is to use a readonly DataContext for fetching objects like this:

        MyDataContext dataContext = new MyDataContext() 
        { 
            DeferredLoadingEnabled = false, 
            ObjectTrackingEnabled = false 
        };

The objects obtained from this context can be attached to another context but only applies to some scenarios.