Sunday, February 8, 2009

LINQ - Detaching DataContext

I took the code from here by and modified it so I could just use an extension class instead of having to change the model. Besides, it is more fun to use the new features of .NET 3.5 :)

using System.Data.Linq;
using System.Data.Linq.Mapping;

public static class ExtendedDataContext
{
public static T Detach(this DataContext dc, T entity) where T : class, new()
{
if (entity == null)
return null;

//create a copy of the entity
object entityCopy = new T();

//enumerate the data member mappings for the entity type
foreach (MetaDataMember member in dc.Mapping.GetMetaType(typeof(T)).DataMembers)
{
//skip associations and deferred members
if (member.IsAssociation || member.IsDeferred)
continue;

//copy the member value
member.StorageAccessor.SetBoxedValue(ref entityCopy, member.StorageAccessor.GetBoxedValue(entity));
}

return (T)entityCopy;
}
}



Code in use
User detachedUser = ((DataContext)db).Detach(user);
db.Users.Attach(detachedUser, true);
db.SubmitChanges();