Saving complex view model using Entity Framework 4.3

1.1k Views Asked by At

I have Customer, Order and OrderItem tables. OrderItem.OrderID points to Order.ID; and Order.CustomerID points to Customer.ID i.e. the common Customer -> Order -> OrderItem setup.

And I have a view model – Customer which contains Order objects and then OrderItem objects as well.

If the user creates a new Customer, new Order and new OrderItems on a view, which are then bound to the Customer view model object (containing all Customer, Order, OrderItem data); is there a way to save this Customer view model using EF?

My confusion comes from the fact that, since Customer, Order, OrderItem(s) are all new records; which means the Customer.ID (auto-incremented number) has not been generated yet (record not saved yet); so how does EF know what ID to use when saving Order.CustomerID?

Do I need to save Cusomer first, get the Customer.ID, then save Order, then get Order.ID and then save OrderItem(s)?

Thanks.

2

There are 2 best solutions below

0
On

You just call this:

context.Customers.Add(customer);
context.SaveChanges();

and if everything is correctly configured in your mapping EF will understand relations and correctly save customer first, retrieve its Id and use it for saving related orders. It will handle order items in the same way.

0
On

As long as you establish the objects relationships before saving it should work

customer.Orders = new List<Orders>();
customer.Orders.Add(order);

order.OrderItems = new List<OrderItems>();
order.OrderItems.Add(orderItem);

context.Customer.Add(customer);
context.SaveChanges();