0

I've a question and I hope this is possible. I want to map properties from an nested class into his parent class (without creating a new object, this should be the same object) Below I've attached an example.

I want to map the properties from the Bar class (which is in de Foo class) to the properties on the Bar class. So I've an instance of Foo and SomeIntProperty and SomeString property has their default value, the Bar property instead has some real values. I want to map those values from the Bar property from Foo to Foo. Is this possible, and is it possible without specifying a mapper for the properties? My classes contains a lot of properties..

I find it really hard to explain, sorry if it is still confusing.

    public class Foo
{
    public int SomeIntProperty { get; set; }
    public string SomeStringProperty { get; set; }

    // the properties from this Bar instance should be mapped to the properties above.
    public Bar Bar { get; set; }
}

public class Bar
{
    public int SomeIntProperty { get; set; }
    public string SomeStringProperty { get; set; }
    public bool ThisPropertyDoesntExistsOnFooClass { get; set; }
}
MRteR
  • 3
  • 3

1 Answers1

0

You can use Automapper as described here: Automapper: Update property values without creating a new object

Ivan Yurchenko
  • 3,762
  • 1
  • 21
  • 35
  • Thank you for your solution. It's just not quite what I mean, in your provided solution setting a property value on Foo will affect Bar. The properties should be independent of each other. At a certain point I would like to transfer the property values from Bar to Foo. When I set a property on Foo it should not affect Bar and vice versa. I’ve thought to use reflection to do the trick but there must be a more fancy quicker way. – MRteR Nov 16 '17 at 07:43
  • @MRteR Just use Automapper then. https://stackoverflow.com/questions/2374689/automapper-update-property-values-without-creating-a-new-object – Ivan Yurchenko Nov 16 '17 at 20:59
  • Could you please post your comment as an answer so I can accept it? – MRteR Nov 27 '17 at 22:23
  • @MRteR Sure, I updated my answer. Glad that it helped you. :) – Ivan Yurchenko Nov 27 '17 at 22:29