Tuesday, May 04, 2010

Entity Framework: Inserting objects with parent/child relationships

Test model:
image

Code to add a person object and associated addresses:

using (Model1Container mctx = new Model1Container())
{
Person person = new Person();
person.Name = "Raj";

Address address1 = new Address();
address1.Line1 = "Line 1";

person.Addresses.Add(address1);

Address address2 = new Address();
address2.Line1 = "Line 2";

person.Addresses.Add(address2);

mctx.People.AddObject(person);

mctx.SaveChanges();
}

Once SaveChanges is called, all objects (person, address1, address2) will all have the updated Id values, which can be used for other purposes in your code.

1 comment:

Kunal Uppal said...

What if you try to add two new address objects to an existing parent object?.. Can you show a sample for that