How can a child entity move from one parent to another?

I'm converting an application from my custom ORM to Entity Framework with .Net 4. Things are going pretty well, but I'm unsure how to move a child item to another parent. I'm not sure what pattern I should follow.

With the ORM, I generated methods such as:

public void MoveTo_Item(Parent.Row destination)
    _inMovement = true;
    parent_id =;
    _inMovement = false;


  • _inMovement == true prevented _parent_Item.Child_Items.Remove/Add(this) from triggering a delete/insert in the DB; and
  • parent_id = triggered the update in the DB.

The child item itself has child items, so don't think I can just do parent1.Remove(item) followed by parent2.Add(item).

How does one properly change the parent item with EF .Net 4?


In EF, if your navigation properties are set up correctly, it should be simply a matter of (made-up names here, obviously)

Child child = sourceParent.Children.First();  // or whatever

child.ParentObject = destinationParent;

btw, if your custom ORM hit the database every time objects were manipulated (which must have been quite resource-intensive, no?), you're going to need to adjust to the EF way of working, where the database isn't hit unless you explicitly say so.

Below is solution for Self Tracking Entities.

Use ObjectSet.Detach(YourObject) to detach object from one object set.

There are two functions for attachment. Attach should be used if your object is loaded from DB and you expect EF to use Update statement for it. Attach is function that you need to use for detached entities.

AddObject should be used if you just created your Entity in application and it is not already in DB (Insert statement to be used).

See MSDN for more details.

Need Your Help