Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq2Sql: Manage DataContext

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

like image 245
Niels Bosma Avatar asked Dec 30 '22 07:12

Niels Bosma


2 Answers

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.

like image 89
Aleris Avatar answered Jan 13 '23 21:01

Aleris


The PLINQO framework generates detach for all entities making it easy to detach and reattach objects without receiving that error.

public void Foo()
{
   CompanyDataContext db = new CompanyDataContext();
   Client client = (select c from db.Clients ....).Single();
   // makes it possible to call detach here
   client.Detach();
   Bar(client);
}

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

Here is the article that describing how the detach was implemented. http://www.codeproject.com/KB/linq/linq-to-sql-detach.aspx

like image 31
Shannon Davidson Avatar answered Jan 13 '23 21:01

Shannon Davidson