Created
October 18, 2019 02:25
-
-
Save xltuo/c718d0d7cd6e135de1482cb979b212b0 to your computer and use it in GitHub Desktop.
Entity Framework copy/clone of an entity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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