L2S - retrieve an entity, modify it, and insert it as new RRS feed

  • Question

  • I got a situation where I need to maintain two "copies" of a record in the database. for simplicity, the db table is:

    Details(Id, Title, Description, IsStaffCopy)

    where ID is the PK (not identity, but unique), IsStaffCopy is a bit field

    So I need to get the record where IsStaffCopy = 0, then set IsStaffCopy to 1, and insert the record as new.

    var original = ctc.Details.Single(item => item.Id == 1)
    original.IsStaffCopy = true;
    original.Id = 0 // do this to make the context think it's a new record?

    var newCtx = new DetailsDataContext(...)

    Is that possible, or will the error come up saying that I'm attaching an entity retrieved from another context?

    I've been getting that error all morning, in a slighlty more complicated scenario, but apparently even though the datacontext an entity is associated with goes out of scope, it's impossible to insert that entity.

    Thanks for any help. I'm hoping I don't need detach code though.
    Friday, February 19, 2010 9:37 PM


  • Clone the entity before reinserting. You can either use reflection+l2s mapping (copy only the persisted non-autogen members), or the datacontractserializer to do this. Whichever you prefer...


    internal static T CloneEntity<T>(T originalEntity)
        Type entityType = typeof(T);

        DataContractSerializer ser =
            new DataContractSerializer(entityType);

        using (MemoryStream ms = new MemoryStream())
            ser.WriteObject(ms, originalEntity);
            ms.Position = 0;
            return (T)ser.ReadObject(ms);

    Kristofer - Huagati Systems Co., Ltd.
    Cool tools for Linq-to-SQL and Entity Framework: (add-in with new features for the L2S and EF designers in VS2008 and VS2010) (Query profiler for Linq-to-SQL and LLBLGen Pro)
    Tuesday, February 23, 2010 12:47 AM

All replies