Code First: Independent associations vs. Foreign key associations?

前端 未结 4 1262
醉梦人生
醉梦人生 2020-11-22 01:07

I have a mental debate with myself every time I start working on a new project and I am designing my POCOs. I have seen many tutorials/code samples that seem to favor fo

4条回答
  •  情书的邮戳
    2020-11-22 01:20

    Independent association doesn't work well with AddOrUpdate that is usually used in Seed method. When the reference is an existing item, it will be re-inserted.

    // Existing customer.
    var customer = new Customer { Id = 1, Name = "edit name" };
    db.Set().AddOrUpdate(customer);
    
    // New order.
    var order = new Order { Id = 1, Customer = customer };
    db.Set().AddOrUpdate(order);
    

    The result is existing customer will be re-inserted and new (re-inserted) customer will be associated with new order.


    Unless we use the foreign key association and assign the id.

     // Existing customer.
    var customer = new Customer { Id = 1, Name = "edit name" };
    db.Set().AddOrUpdate(customer);
    
    // New order.
    var order = new Order { Id = 1, CustomerId = customer.Id };
    db.Set().AddOrUpdate(order);
    

    We have the expected behavior, existing customer will be associated with new order.

提交回复
热议问题