Mapping dictionaries with AutoMapper

后端 未结 2 1884
名媛妹妹
名媛妹妹 2020-12-03 14:03

Given this these classes, how can I map a dictionary of them?

public class TestClass
{
    public string Name { get; s         


        
相关标签:
2条回答
  • 2020-12-03 14:29

    The problem you are having is because AutoMapper is struggling to map the contents of the Dictionary. You have to think what it is a store of - in this case KeyValuePairs.

    If you try create a mapper for the KeyValuePair combination you will quickly work out that you can't directly as the Key property doesn't have a setter.

    AutoMapper gets around this though by allowing you to Map using the constructor.

    /* Create the map for the base object - be explicit for good readability */
    Mapper.CreateMap<TestClass, TestClassDto>()
          .ForMember( x => x.Name, o => o.MapFrom( y => y.Name ) );
    
    /* Create the map using construct using rather than ForMember */
    Mapper.CreateMap<KeyValuePair<string, TestClass>, KeyValuePair<string, TestClassDto>>()
          .ConstructUsing( x => new KeyValuePair<string, TestClassDto>( x.Key, 
                                                                        x.Value.MapTo<TestClassDto>() ) );
    
    var testDict = new Dictionary<string, TestClass>();
    var testValue = new TestClass()
    {
        Name = "value1"
    };
    testDict.Add( "key1", testValue );
    
    /* Mapped Dict will have your new KeyValuePair in there */
    var mappedDict = Mapper.Map<Dictionary<string, TestClass>,
    Dictionary<string, TestClassDto>>( testDict );
    
    0 讨论(0)
  • 2020-12-03 14:29

    AutoMapper has changed a bit so it looks more like:

    CreateMap<Thing, ThingDto>()
         .ReverseMap();
    CreateMap<Thing, KeyValuePair<int, ThingDto>>()
         .ConstructUsing((t, ctx) => new KeyValuePair<int, ThingDto>(t.id, ctx.Mapper.Map<ThingDto>(t)));
    
    0 讨论(0)
提交回复
热议问题