【问题标题】:How to map Object to KeyValuePair<char, string> using AutoMapper?如何使用 AutoMapper 将对象映射到 KeyValuePair<char, string>?
【发布时间】:2020-03-31 05:17:30
【问题描述】:

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

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

谢谢!


Asp.Net Core 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;
                }

【问题讨论】:

标签: c# automapper asp.net-core-3.1 keyvaluepair automapper-9


【解决方案1】:

通过以下方式解决:

CreateMap<Symbol, KeyValuePair<char, string>>()
                .ConstructUsing(sym => new KeyValuePair<char, string>(sym.Letter, sym.ImgSource));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多