locked
Clone entity with child entities and update foreign keys of child entities after insert RRS feed

  • Question

  • I need to clone a parent entity which has many child entities with foreign relationships to the parent (i.e. parentId).

    I have no problem cloning an entity but the newly cloned entity then needs to:

    1. Be inserted into the database and get the next available PK (which also works fine)

    2. And all foreign key values of all child entities updated to the new PK created in step 1

    My problem is with step 2.

    How best can I perform this action or is there a better way to go about this?

    If I set the PK of the parent entity to 0 should EF handle this for me with child entities during an insert?

    Tuesday, September 20, 2016 8:30 PM

Answers

  • Hi DarrenOD,

    >>How best can I perform this action or is there a better way to go about this?

    As far as I know, it seems that we need create a new object and pass the value to this new object, like this:

     using (var db = new BloggingContext())
                {
                    var blog = db.Blog.Find(1003);
    
                    var newblog = new Blog() { Url = blog.Url };
    
                    foreach (var post in blog.Post)
                    {
                        var newPost = new Post() { Title = post.Title, Content = post.Content };
                        newblog.Post.Add(newPost);
                    }
    
    
                    db.Blog.Add(newblog);
                    db.SaveChanges();
    
                    Console.WriteLine("OK");
                }

    >>If I set the PK of the parent entity to 0 should EF handle this for me with child entities during an insert?

    If you set the PK of the parent entity to 0 and then run SaveChanges(), it will throw an exception.

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Wednesday, September 21, 2016 6:53 AM