'How to map Object to KeyValuePair<char, string> using AutoMapper?
I'm trying to map my object model to a KeyValuePair<char, string>
but my results are KeyValuePairs
where Key = null and Value = null.
What's the correct way to do this?
Model:
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; }
}
Profile:
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();
}
}
Attempt:
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;
}
Solution 1:[1]
Solved by using the following :
CreateMap<Symbol, KeyValuePair<char, string>>()
.ConstructUsing(sym => new KeyValuePair<char, string>(sym.Letter, sym.ImgSource));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | roonz11 |