簡體   English   中英

AutoMapper-映射不起作用

[英]AutoMapper - mapping doesn't work

我想將KeyValuePair對象的簡單集合映射到我的自定義類。 不幸的是我只有一個例外

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]

以最簡單的形式編碼來重現此問題

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();
    }
}

我以相同的方式(沒有枚舉)創建了其他映射,並且它們可以工作,因此這一定是一個問題,但是如何解決呢? 我必須要注意的事情很簡單。

ConstructUsing僅指示AutoMapper如何構造目標類型。 在構造目標類型的實例之后,它將繼續嘗試映射每個屬性。

相反,您需要的是ConvertUsing ,它告訴AutoMapper您要接管整個轉換過程:

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

示例: https //dotnetfiddle.net/Gxhw6A

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM