add an entity to associated entities

This article demonstrates how to add an order to an existing customer. Inserting a new object to a single entity is explained in the article - Inserting new objects in EntityFramework.

To demonstrate this example, I have considered two entities - Customer and Order.

Steps to add entity to associated entities

Query the customer to whom we want to add orders.
Create a new order and set the properties.
The newly created order is joined with the customer.


How does this happen?

The ObjectContext creates a new ObjectStateEntry for the Order and its state is set as Added. When we call SaveChanges()method, the object context sends an Insert command and database is updated with new changes.

var context = new SalesOrderManagementEntities();
var customer = context.Customer.Where(c => c.Name == "kris").First();
var order = new Order();
order.Total = 900;
order.Customer = customer;
context.SaveChanges();