0

我正在尝试将我的对象模型映射到 KeyValuePair,但我的结果是 KeyValuePairs,其中 Key = null 且 Value = null。

这样做的正确方法是什么?

谢谢!


ASP.NET 核心 3.1

AutoMapper 9.0.0

AutoMapper.Extensions.Microsoft.DependencyInjection 7.0.0


模型:

public class Symbol
    {
        public int Id { get; set; }
        public int TemplateId { get; set; }
        public Template Template { get; set; }
        public char Letter { get; set; }
        public string ImgSource { get; set; }
    }

轮廓:

    public class AutoMapping : Profile
    {
        public AutoMapping()
        {
            CreateMap<Symbol, KeyValuePair<object, object>>()
                      .ForMember(dest => dest.Key, opt => opt.MapFrom(src => src.Letter))
                      .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.ImgSource))
                      .ReverseMap();

        }
    }

试图:

                using (_dbContext)
                {
                    var q = await _dbContext.Symbol
                        .Where(x => x.TemplateId == templateId)
                        .OrderBy(x => x.Letter)
                        .Select(x => _mapper.Map<KeyValuePair<char, string>>(x))
                        .ToListAsync();

                    //return _mapper.Map<List<KeyValuePair<char, string>>>(q);
                    return q;
                }
4

1 回答 1

0

通过使用以下方法解决:

CreateMap<Symbol, KeyValuePair<char, string>>()
                .ConstructUsing(sym => new KeyValuePair<char, string>(sym.Letter, sym.ImgSource));
于 2020-03-31T16:14:34.730 回答