简体   繁体   中英

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?

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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM