Entity Framework duplicate object and all child properties

c# entity-framework


Typical structure

public class Page
    public int PageId { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public virtual List<Section> Sections { get; set; }

public class Section
    public int SectionId { get; set; }
    public int PageId { get; set; }
    public virtual Page Page { get; set; }
    public virtual List<Heading> Headings { get; set; }

public class Heading
    public int HeadingId { get; set; }
    public int SectionId { get; set; }
    public virtual Section Section { get; set; }

Although my actual structure contains more levels, it's important to note that this should be sufficient to convey my goals.

I then fill myPage object I then duplicate that object and make a few little adjustments to its characteristics.Page i.e. Prop1 , Prop2

Page pageFromDb = getPageMethod();
Page clonedPage = pageFromDb.Clone();
clonedPage.Prop1 = clonedPage.Prop1 + " Cloned";
addPageMethod(clonedPage); //Adds the page to db

In the aforementioned instanceclonedPage Fine structure and a newPage to the database is added. However, I think this is true because kid objects have established Ids and their relationships are always one to many. the initial itempageFromDb will no longer have any children once the entity framework replaces it with newSection items for cloned peoplePage that will updateSection.PageId visit the freshly added page.

I think the solution to this would be toforeach , foreach , etc., with all of the IDs set to0 Entity framework will make new records for each item before inserting. Is there a simpler or better approach to copy an object in an environment using entity framework?

7/18/2014 3:08:38 PM

Popular Answer

Entity Framework needs all entities in the graph to be disconnected from the context in which the root entity was retrieved in order to treat the clone as a whole new object graph when persisting the graph.

You can carry out this utilizing theAsNoTracking on the circumstances, a procedure.

For instance, this will extract the graph of a page and its related sections from the database and disable tracking. This is essentially a copy because adding it to your Page DbSet and saving it will generate a brand-new object graph in the database. I.e., new Page and Section entities as necessary. Be aware that you won't need to call yourClone method.

var clone = context.Pages
    .Including(pages => pages.Sections)
context.SaveChanges(); // creates an entirely new object graph in the database
7/18/2014 3:44:13 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow