Code First: Independent associations vs. Foreign key associations?

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<Customer>().AddOrUpdate(customer);

// New order.
var order = new Order { Id = 1, Customer = customer };
db.Set<Order>().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<Customer>().AddOrUpdate(customer);

// New order.
var order = new Order { Id = 1, CustomerId = customer.Id };
db.Set<Order>().AddOrUpdate(order);

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

Leave a Comment