AutoMapper字典拼合 [英] AutoMapper Dictionary Flattening

查看:131
本文介绍了AutoMapper字典拼合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Dictionary<User, bool>

用户如下:

 public class User {
   public string Username { get; set; }
   public string Avatar { get; set;
}

第二种类型bool指示此用户是否是已登录用户的朋友. 我想将此字典拼凑成> UserDto,其定义为:

The second type, bool, indicates whether this user is a friend of the logged in User. I want to flatten this Dictionary into a List<UserDto> UserDto is defined as:

public class UserDto {
   public string Username { get; set; }
   public string Avatar { get; set; }
   public bool IsFriend { get; set; }
}

IsFriend代表字典的值.

我该怎么做?

推荐答案

您应该只需要一个映射就可以做到这一点 1 :

You should be able to do this with just one mapping1:

您需要将KeyValuePair<User, bool>映射到UserDto.为了使AutoMapper能够将字典的内容映射到我们最终创建的List<T>的内容,这是必要的(有关更多说明,请参见

You need to map a KeyValuePair<User, bool> to UserDto. This is necessary for AutoMapper to be able to map the contents of the dictionary to the contents of the List<T> we're ultimately creating (more of an explanation can be found in this answer).

Mapper.CreateMap<KeyValuePair<User, bool>, UserDto>()
    .ForMember(dest => dest.Username, opt => opt.MapFrom(src => src.Key.UserName))
    .ForMember(dest => dest.Avatar, opt => opt.MapFrom(src => src.Key.Avatar))
    .ForMember(dest => dest.IsFriend, opt => opt.MapFrom(src => src.Value));

然后,在您的.Map调用中使用映射:

Then, use the mapping in your .Map call:

Mapper.Map<Dictionary<User, bool>, List<UserDto>>(...);

您不需要自己映射集合,因为只要您将集合的 contents 相互映射,AutoMapper就可以处理将Dictionary映射到List的过程(在我们的例子中是KeyValuePair<User, bool>UserDto).

You don't need to map the collections themselves, as AutoMapper can handle mapping the Dictionary to a List as long as you've mapped the contents of the collections to each other (in our case, KeyValuePair<User, bool> to UserDto).

编辑:这是另一种解决方案,不需要将每个User属性映射到UserDto:

Edit: Here's another solution that doesn't require mapping every User property to UserDto:

Mapper.CreateMap<User, UserDto>();
Mapper.CreateMap<KeyValuePair<User, bool>, UserDto>()
    .ConstructUsing(src => Mapper.Map<User, UserDto>(src.Key))
    .ForMember(dest => dest.IsFriend, opt => opt.MapFrom(src => src.Value));

1 使用AutoMapper 2.0

这篇关于AutoMapper字典拼合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆