Updating an instance from another of the same type with conditions RRS feed

  • Question

  • I had some code that took flat POCOs composed of nullable types and updated one based on another with a condition that the the property was only copied over if it was not null. There were several semantics involved, like binary (de)serialization to effectively clone the objects ensuring no references existed with the final merged model.

    The situation has now evolved where the models contain properties based on other complex types. In this case, I can no longer flatly enumerate the PropertyInfo of the object, I need to recursively do this. The models follow strict guidelines and therefor the types can reliably be enumerated without traversing built in types etc.

    The problem is I know from experience that the properties are enumerated alphabetically and it appears consistent but this behavior cannot be depended on. I can produce an algorithm to identity properties based on parent model and property name etc and then associate them all in order to make the comparisons, however I wonder if something like this exists so i don't need to re-invent the wheel.

    I'd be grateful for any opinions.

    Wednesday, February 7, 2018 10:04 PM


All replies

  • Hello Ritmo2k,

    I really recommend looking at Automapper.  Why re-invent the wheel as you say.

    Cheers, Jeff

    Thursday, February 8, 2018 9:47 PM
  • I have heard of AutoMapper before but I have never used it and didn't actually know what it was for. I'm not sure exactly how I feel right now, I spent hours writing piles of buggy code to clone and merge and I am still not finished. I just replaced it all with 3 lines of code in each case and its mostly passing all the tests:)

    Unbelievable, I just need to workout a generic way to solve a case where a property of type string[] that is null on both sides of a merge ends up getting reanimated as empty array.

    Can't thank you enough!
    Thursday, February 8, 2018 11:56 PM
  • Thanks Ritmo2k.  You made my day.  Glad it is working for the most part.  If you find you want a bit of help, I suggest another post on the community or stack overflow.

    (sent by chilberto on his other account)

    Friday, February 9, 2018 12:08 AM