Entity Framework 5 POCOs - creating and managing relationships

前端 未结 1 1838
[愿得一人]
[愿得一人] 2021-01-23 16:34

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()         


        
相关标签:
1条回答
  • 2021-01-23 17:02

    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.

    0 讨论(0)
提交回复
热议问题