Rediscovering the Obvious

…stumbling in the footsteps of greatness

Linq entities and calling Attach()

without comments

Back to tech, for now.

I like Linq to SQL. A LOT. However, there have been a handful of things that have annoyed me, and one of them is the story around serialization and disconnected entities. They’ve built a nice engine for it (DataContract-based), and really optimized it for the case where you’re getting a data set from a disconnected client and storing the changes to the server. Except, annoyingly, there’s no good way to tell if an entity is already attached to a specific context. And, you can’t call .Attach() on something unless it’s currently floating. Did I mention there’s no .Detach? The only way I know of for it to be detached is to have just been Deserialized.

Well, we’re storing entities across calls. In one case, it’s in the session. In another, it’s in memcached. Either way, there are cases were we don’t know if our object that needs updating to the DB has been loaded fresh during the current call or not. Well, it’s not a documented approach, but by looking at the code, I can find out that doing this will work:

 // HACK: This will prevent a reattachment by identifying that the
// provided project was already available in this context.
Project originalProject = db.Projects.GetOriginalEntityState(project);
if ( originalProject == null )

Written by erwilleke

April 4th, 2008 at 2:58 pm

Posted in Uncategorized

Leave a Reply