shod
shod

Reputation: 3

Using AutoMapper, is it possible to map a property value to a property?

I'm using AutoMapper for C# and I'm trying to convert a property value into a property name.

Consider the following:

public class ClassA
{
    public string ParamA { get; set; }
    public string ParamB { get; set; }
}

public class ClassB
{
    public string Name { get; set; }
    public string Val { get; set; }
}

I have a list of ClassB instances and I'm trying to convert the value of "Val" property from ClassB into the correct property of ClassA based on the value of "Name":

ClassB b1 = new ClassB() {Name = "ParamA", Val = "ValueA"};
ClassB b2 = new ClassB() {Name = "ParamB", Val = "ValueB"};
ClassB b3 = new ClassB() {Name = "ParamC", Val = "ValueC"};
List<ClassB> listB = new List<ClassB>() {b1, b2, b3};

So using listB I'm trying to create an object of type ClassA with ParamA = "ValueA" and ParamB = "ValueB", is it possible using AutoMapper or any other tool?

Upvotes: 0

Views: 131

Answers (2)

Wapac
Wapac

Reputation: 4178

I have once found this piece of code on SO and I am using it ever sinc e for these kinds of things. You put this extension method into your class:

    public object this[string propertyName]
    {
      get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
      set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
    }

and then you can use [] to do

ClassA a;
ClassB b;
...
a[b.Name] = b.Val;

Upvotes: 1

Yacoub Massad
Yacoub Massad

Reputation: 27861

is it possible using AutoMapper or any other tool?

You can use Reflection to do something like this:

ClassA a = new ClassA();

foreach (var b in listB)
{
    typeof(ClassA)
        .GetProperty(b.Name) //Get property of ClassA of which name is b.Name
        .SetValue(a , b.Val); //Set the value of such property on object a
}

Please note that based on your question, ClassA should have a property named ParamC.

Upvotes: 1

Related Questions