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();
No comments:
Post a Comment