简体   繁体   中英

AutoMapper - mapping doesn't work

I want to map a simple collection of KeyValuePair objects to my custom class. Unfortunatelly I only get an exception

Missing type map configuration or unsupported mapping.

Mapping types:
RuntimeType -> DictionaryType
System.RuntimeType -> AutoMapperTest.Program+DictionaryType

Destination path:
IEnumerable`1[0].Type.Type

Source value:
System.Collections.Generic.KeyValuePair`2[AutoMapperTest.Program+DictionaryType,System.String]

Code in simplest form to reproduce this problem

class Program
{
    public enum DictionaryType
    {
        Type1,
        Type2
    }

    public class DictionariesListViewModels : BaseViewModel
    {
        public string Name { set; get; }
        public DictionaryType Type { set; get; }
    }

    public class BaseViewModel
    {
        public int Id { set; get; }
    }

    static void Main(string[] args)
    {
        AutoMapper.Mapper.CreateMap<
            KeyValuePair<DictionaryType, string>, DictionariesListViewModels>()
            .ConstructUsing(r =>
            {
                var keyValuePair = (KeyValuePair<DictionaryType, string>)r.SourceValue;
                return new DictionariesListViewModels
                {
                    Type = keyValuePair.Key,
                    Name = keyValuePair.Value
                };
            });

        List<KeyValuePair<DictionaryType, string>> collection =
            new List<KeyValuePair<DictionaryType, string>>
        {
            new KeyValuePair<DictionaryType, string>(DictionaryType.Type1, "Position1"),
            new KeyValuePair<DictionaryType, string>(DictionaryType.Type2, "Position2")
        };

        var mappedCollection = AutoMapper.Mapper.Map<IEnumerable<DictionariesListViewModels>>(collection);


        Console.ReadLine();
    }
}

I have other mapping created the same way (without enum) and they works, so it must be a problem, but how to workaround it? It must be something simple that I have problem to note.

ConstructUsing only instructs AutoMapper how to construct the destination type. It will continue to attempt to map each property after constructing an instance of the destination type.

What you want instead is ConvertUsing which tells AutoMapper that you want to take over the entire conversion process:

Mapper.CreateMap<KeyValuePair<DictionaryType, string>, DictionariesListViewModels>()
    .ConvertUsing(r => new DictionariesListViewModels { Type = r.Key, Name = r.Value });

Example: https://dotnetfiddle.net/Gxhw6A

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