27

I have a situation when I cant just update original record in database, but instead make a new record, copy all fields from old and apply changes to new one. (something like this if translated to code)

var original = from _orig in context.Test where _orig.id == 5 select _orig;
Test newTest = new Test();
newTest = original;
newTest.id = 0;
context.Test.InsertOnSubmit(newTest);
context.SubmitChanges();
original.parent_id = newTest.id;
original.isActive = 0;

which gives the following exception:

Cannot add an entity that already exists.

Is it possible to make it work without manually copying every field?

6 Answers 6

31

This should work:

Generic Clone() Method

This method will create a full clone of any object by serializing it. The original idea came from both here and here.

/// <summary>
/// Clones any object and returns the new cloned object.
/// </summary>
/// <typeparam name="T">The type of object.</typeparam>
/// <param name="source">The original object.</param>
/// <returns>The clone of the object.</returns>
public static T Clone<T>(this T source) {
    var dcs = new DataContractSerializer(typeof(T));
    using(var ms = new System.IO.MemoryStream()) {
        dcs.WriteObject(ms, source);
        ms.Seek(0, System.IO.SeekOrigin.Begin);
        return (T)dcs.ReadObject(ms);
    }
}

Your Code Example

Now with the help of the above extension method, your code should work if tweaked a little bit:

var original = from _orig in context.Test where _orig.id == 5 select _orig;
Test newTest = original.Clone();
newTest.id = 0;
context.Test.InsertOnSubmit(newTest);
context.SubmitChanges();
original.parent_id = newTest.id;
original.isActive = 0;
5
  • Only problem is that if any relatedEntities hang off of the original entity when cloned the EntityKey is still populated with the original keys when you Add as newTest.
    – Mark
    Feb 4, 2010 at 12:08
  • @Mark - When I implemented similar functionality I would .Load() any child entities of the object I was cloning, otherwise the serializer wouldn't see them and would skip them. Once they were loaded, cloning the object worked perfectly and LINQ-to-SQL automatically inserted new child records with the new cloned parent's keys on .SubmitChanges(). Feb 4, 2010 at 16:17
  • What do you mean by .Load()? I am doing a LoadWith on all the collections to make them serialized, but the one to one entities are null after the clone (even though ids are set) and I'm not crazy about the LoadWith. Mar 2, 2012 at 21:32
  • When I implement this method and run it I get: Message = "Object graph for type 'mymodel.submodel' contains cycles and cannot be serialized if reference tracking is disabled." ... How can you fix this ?
    – guiomie
    Oct 11, 2013 at 18:39
  • @guiomie - That generally means you have circular references in your object. Oct 14, 2013 at 19:57
8

Is it possible to make it work without manually copying every field?

Yes - don't manually copy every field:

You could use AutoMapper.

Set up somewhere (called once at program start):

AutoMapper.Mapper.CreateMap<MyObject, MyObject>()
// don't map the id to stop conflicts when adding into db
    .ForMember(a => a.Id, a => a.Ignore()); 

Then call:

var newObject = AutoMapper.Mapper.Map<MyObject>(oldObject);
1
  • While the implementation of Automapper is outdated this was the best way to go for me. I'd advise anyone looking to use this to look at the Getting Started page for AutoMapper.
    – LWood
    Nov 28, 2019 at 14:28
6

Using Reflection, you can easily copy each attribute that is not DbGenerated. This method is probably not very performant, but it will work in a pinch.

public static T Clone<T>(this T source)
{
    var clone = (T)Activator.CreateInstance(typeof(T));
    var cols = typeof(T).GetProperties()
        .Select(p => new { Prop = p, Attr = (ColumnAttribute)p.GetCustomAttributes(typeof(ColumnAttribute), true).SingleOrDefault() })
        .Where(p => p.Attr != null && !p.Attr.IsDbGenerated);
    foreach (var col in cols)
        col.Prop.SetValue(clone, col.Prop.GetValue(source, null), null);
    return clone;
}
1
  • 1
    Is ColumnAttribute supposed to derive from System.ComponentModel.DataAnnotations.Schema or System.Data.Linq.Mapping.DataAttribute ?
    – Eric Wu
    May 16, 2017 at 13:29
4

You could use reflection to iterate over the properties and set them

  foreach (var prop in original.GetType().GetProperties())
  {
     prop.SetValue(newTest, prop.GetValue(original,null), null);
  }

Obviously this will need to be expanded to be less error prone, but it could be a good start.

This will certainly have a slower runtime than if the properties were written out manually, I'd imagine.

3

It might be better if you create a stored proc and copy the objects in there instead of wasting time on linq-sql limitations. You can handle errors and other problems easily in sql syntax.

2

You may also want to look into PLINQO. It has the ability to clone, detach, attach, serialize to xml, serialize to binary, many to many relationships, etc... all right out of the box so you don't have to deal with these features that should've been included in the first place.

http://www.plinqo.com/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.