Update Master Record with new added Child object.-Collection of common programming errors

Hi Alex

What error message do you get when you try to add. It will help to know which rule you broke and therefore which method you need to add the child.

The way to add a “child” depends on a few things.

I believe that your “parent” is already in the objectContext.

In many cases, it is easier to start with the child and set it’s parent

ChildObject.parent=o

However, starting with the parent, you have to be more careful.

If the child is NEW (no EntityKey), then you can ADD it to the child collection of the parent

o.ChildObjects.Add(ChildObject)

This will also make sure that when you SaveChanges, the childobject gets saved to the db.

If the child is not new (has an EntityKEy) and is managed by the ObjectContext, then you can Attach it to the child collection.

o.ChildObjects.Attach(ChildObject)

If the child is not new (has an EntityKey) and is not being managed by the ObjectContext, then you need to first attach it to the ObjectContext and then attach it to the collection.

aEntity.Attach(ChildObject)

o.ChildObjects.Attach(ChildObject)

hth

julie