views:

1389

answers:

3

Hi guys,

What would be considered the best practice in duplicating [cloning] a LINQ to SQL entity resulting in a new record in the database?

The context is that I wish to make a duplicate function for records in a grid of an admin. website and after trying a few things and the obvious, read data, alter ID=0, change name, submitChanges(), and hitting an exception, lol. I thought I might stop and ask an expert.

I wish to start with first reading the record, altering the name by prefixing with "Copy Of " and then saving as a new record.

+6  A: 

Create a new instance and then use the linq mapping classes together with reflection to copy member values.

E.g.

public static void CopyDataMembers(this DataContext dc, object sourceEntity, object targetEntity)
{
    //get entity members
    IEnumerable<MetaDataMember> dataMembers = from mem in dc.Mapping.GetTable(sourceEntity.GetType()).RowType.DataMembers
                                              where mem.IsAssociation == false
                                              select mem;

    //go through the list of members and compare values
    foreach (MetaDataMember mem in dataMembers)
    {
        object originalValue = mem.StorageAccessor.GetBoxedValue(targetEntity);
        object newValue = mem.StorageAccessor.GetBoxedValue(sourceEntity);

        //check if the value has changed
        if (newValue == null && originalValue != null || newValue != null && !newValue.Equals(originalValue))
        {
            //use reflection to update the target
            System.Reflection.PropertyInfo propInfo = targetEntity.GetType().GetProperty(mem.Name);
            propInfo.SetValue(targetEntity, propInfo.GetValue(sourceEntity, null), null);

            //setboxedvalue bypasses change tracking - otherwise mem.StorageAccessor.SetBoxedValue(ref targetEntity, newValue); could be used instead of reflection
        }
    }
}

...or you can clone it using the DataContractSerializer:

internal static T CloneEntity<T>(T originalEntity) where T : someentitybaseclass
{
    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);
    }
}
KristoferA - Huagati.com
Will take a look Kristofer.
GONeale
Great answer! This is working, I did contemplate reflection. How do you feel about this solution? I suppose any built-in Clone() I was expecting would perform a similar operation..
GONeale
If you have read-only properties in your entity you need to check if the property has a setter before calling propInfo.SetValue. You can do that my checking if propInfo.GetSetMethod() returns a non-null value.
pbz
+3  A: 

I was stuck with the same problem and Kristofer's code worked perfectly, many thanks!

In case someone is interested, I slightly modified his code so that instead of accepting the target entity as a parameter, it creates a new object and returns it. Also I have made the sourceEntity parameter to be generic:

 public static T CloneEntity<T>(this DataContext dc, T sourceEntity) where T:class, new()
 {
     var targetEntity = new T();
     //... original method code...
     return targetEntity;
 }

Then I can do the following:

dataContext.MyEntities.Attach(dataContext.CloneEntity(theEntity));
Konamiman
A: 

If you load entity from DataContext with set ObjectTrackingEnabled to false then you can insert this entity as new in another DataContext

DataContext db1 = new DataContext();
DataContext db2 = new DataContext();

db2.ObjectTrackingEnabled = false;

MyEntity entToClone = db2.Single(e => e.Id == id);

// ... change some data if it is needed

db1.MyEntities.InsertOnSubmit(entToClone);
db1.SubmitChanges();
Peter K.