Skip to content

Instantly share code, notes, and snippets.

@xltuo
Created October 18, 2019 02:25
Show Gist options
  • Save xltuo/c718d0d7cd6e135de1482cb979b212b0 to your computer and use it in GitHub Desktop.
Save xltuo/c718d0d7cd6e135de1482cb979b212b0 to your computer and use it in GitHub Desktop.
Entity Framework copy/clone of an entity
public void CloneObject()
{
//Get entity to be cloned
var source = Context.ExampleRows.FirstOrDefault();
//Create and add clone object to context before setting its values
var clone = new ExampleRow();
Context.ExampleRows.Add(clone);
//Copy values from source to clone
var sourceValues = Context.Entry(source).CurrentValues;
Context.Entry(clone).CurrentValues.SetValues(sourceValues);
//Change values of the copied entity
clone.ExampleProperty = "New Value";
//Insert clone with changes into database
Context.SaveChanges();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment