Linq to sql, copy original entity to new one and save

linq-to-sql

Solution

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;

Problem

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?

Original source