Reputation: 10201
I'm using EF5, POCO database first approach. Let's say I need to create a new customer and a new order:-
var customer = new Customer();
var order = new Order();
order.Customer = customer;
order.CustomerId = customer.Id;
customer.Orders.Add(order);
Do I really have to include those last three lines to set up the relationship? The thing to point out here is that I'm creating the entity hierarchy in memory, and manipulating it for potentially a long time until the user hits "Save".
What's confusing me is the idea of creating several new Customer objects. Each will wind up with an ID of 0 (prior to being persisted). There are various places in my code where I do something with an Order's CustomerId property. If there are several new customers (ID 0) then how do I get the right one? Or should I always use Order.Customer
and never Order.CustomerId
(in which case, is it safe to get rid of the ID assignment in the above code)?
Upvotes: 1
Views: 799
Reputation: 236228
When you are adding new customer, whole graph will be inserted and relations will be setup appropriately. You don't need to setup relations manually (See Add One-to-Many Entities):
var customer = new Customer();
customer.Orders.Add(new Order());
context.Customers.Add(customer);
context.SaveChanges();
When you call Customers.Add
customer entity will be added to context and put into Added
state. Same will happen with all it's related entities (orders) - they will have Added
state. All graph will be inserted to database on SaveChanges
call.
Keep in mind, that this trick will not work for updating graph.
BTW: There is nice MSDN article Defining and Managing Relationships which worth reading.
UPDATE: Here is what happen when you are working with EF:
var customer = new Customer();
var order = new Order();
customer.Orders.Add(order); // order.Customer is null
At this point EF completely not involved. You can manually set Customer of order object. Usually I manage two way associations in Add
or Remove
method. I.e. add order to orders collection, and set owner to this
. It's up to you at this point. By default, order owner will be null
. Next:
context.Customers.Add(customer); // order.Customer is customer, but no ids
Here comes EF. Nothing is persisted to database. BUT EF smart enough to know that order relates to customer, and it will set customer (owner) reference to this particular customer. It is not null
anymore. But, thus nothing is persisted, objects don't have IDs yet.
context.SaveChanges(); // ids updated
Voila. Now EF has inserted objects to database. It received IDs, and updated objects with correct IDs.
Upvotes: 1