无法使用AutoMapper将Dictionary <string,string>映射到dto

时间:2019-08-14 09:29:41

标签: c# automapper

我的数据模型和dto是-

public sealed class User
{
    public long UserId { get; set; }
    public string FullName { get; set; }
    public Dictionary<string, string> References { get; set; }
    public string Token { get; set; }
}

public sealed class ReferenceDto
{
    public string Type { get; set; }
    public string Id { get; set; }
}

public sealed class UserReferenceDto
{
    public long UserId { get; set; }
    public IEnumerable<ReferenceDto> References { get; set; }
    public string Token { get; set; }
}

我正在使用AutoMapper nuget版本8.1.1。我已将个人资料地图创建为-

public sealed class UserProfile : Profile //AutoMapper.Profile
    {
        public UserProfile()
        {
            CreateMap<ReferenceDto, KeyValuePair<string, string>>()
                .ConstructUsing(x => new KeyValuePair<string, string>(x.Type.Trim(), x.Id.Trim()));

            CreateMap<KeyValuePair<string, string>, ReferenceDto>()
                .ConstructUsing(x => new ReferenceDto { Type = x.Key.Trim(), Id = x.Value.Trim() });

            CreateMap<User, UserReferenceDto>(); // Not working
        }
    }

我能够实现映射

var references = _mapper.Map<IEnumerable<ReferenceDto>>(User.References)

但是当我尝试将用户模型映射到UserReferenceDto

var response = _mapper.Map<UserReferenceDto>(User);

我正在映射UserId和Token,但得到ReferenceDto的空集合。尝试了几种方法,但仍然会出现空集合。

现在

var response = _mapper.Map<UserReferenceDto>(User);
response.References = _mapper.Map<IEnumerable<ReferenceDto>>(User.References);

为我工作,但我只想通过_mapper.Map<UserReferenceDto>(User);完成此工作。

0 个答案:

没有答案