Entity Framework, Code First, Update “one to many” relationship with independent associations

前端 未结 2 2046
走了就别回头了
走了就别回头了 2021-02-07 15:41

It took me way too long to find a solution to the scenario described below. What should seemingly be a simple affair proved to be rather difficult. The question is:

Usi

2条回答
  •  名媛妹妹
    2021-02-07 16:36

    I waited for @Martin answer because there are more solutions for this problem. Here is another one (at least it works with ObjectContext API so it should work with DbContext API as well):

    // Existing customer
    var customer = new Customer() { Id = customerId };
    // Another existing customer
    var customer2 = new Customer() { Id = customerId2 };
    
    var target = new Target { ID = oldTargetId };
    // Make connection between target and old customer
    target.Customer = customer;
    
    // Attach target with old customer
    context.Targets.Attach(target);
    // Attach second customer
    context.Customers.Attach(customer2);
    // Set customer to a new value on attached object (it will delete old relation and add new one)
    target.Customer = customer2;
    
    // Change target's state to Modified
    context.Entry(target).State = EntityState.Modified;
    context.SaveChanges();
    

    The problem here is internal state model and state validations inside EF. Entity in unchanged or modified state with mandatory relation (on many side) cannot have independent association in added state when there is no other in deleted state. Modified state for association is not allowed at all.

提交回复
热议问题