Controller action update related entities RRS feed

  • Question

  • User44880335 posted


    I have an HttpPost action that receives the entity from client (Edit).

    I need this entity to be updated in the following manner, I'm using EF 6 Code-First:

    • Set it as Modified
    • It's collection nav-properties:
      • Those with ID = 0 set as Added
      • The others, if it's removed by the client, attach and set as Deleted, otherwise set as Modified
    • It's one-to-one nav-properties should all be set as Modified
    • The one-to-zero/one nav-properties:
      • If ID = 0 - set current as Added and old one attach and set as Deleted
      • Otherwise set as Modified

    Loop in the same manner for all properties and navigation properties of ANY provided entity.

    I tried many approaches, each fail for different reasons, either EF complaining about duplicate IDs, impossible to attach or many other exceptions, I just can't figure out how to do this. I'm sure someone has encountered this fairly trivial scenario before and that a proper solution exists.

    Here are some of my experiments.

    I also tried to load the entire graph (using Include) and then calling TryUpdateModel of the Controller, but this 1) adds all collection items as Added, and doesn't manage Deleted entities.

    Sunday, April 19, 2015 10:09 PM

All replies