Unpacking the AutoMapper Dictionary

I have Dictionary<User, bool>

User:

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

The second type, bool, indicates whether this user is a friend of the user. I want to smooth this Dictionary into 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 represents the meaning of the dictionary.

How can i do this?

+5
source share
3 answers

You should be able to do this with only one mapping 1 :

You need to match KeyValuePair<User, bool>with UserDto. This is necessary so that AutoMapper can display the contents of the dictionary into the content List<T>that we ultimately create (more 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));

Then use matching in your call .Map:

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

, AutoMapper Dictionary List, ( KeyValuePair<User, bool> UserDto).


. , User 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

+11

, , , , .Net- () automapper

public static IMappingExpression<Dictionary<string, string>, TDestination> ConvertFromDictionary<TDestination>(
        this IMappingExpression<Dictionary<string, string>, TDestination> exp)
{
    foreach (PropertyInfo pi in typeof(TDestination).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
    {
        exp.ForMember(propertyName, cfg => cfg.MapFrom(r => r[propertyName]));
    }
    return exp;
}

:

Mapper.CreateMap<Dictionary<string, string>, TDestination>().ConvertFromDictionary();

TDestination .NET-. Func/Action , . ( )

Eg.

if (customPropNameMapFunc != null && !string.IsNullOrEmpty(customPropNameMapFunc(propertyName)))
{
   exp.ForMember(propertyName, cfg => cfg.MapFrom(r => r[customPropNameMapFunc(propertyName)]));
}
0

For something as simple as this, a quick LINQ query will be executed. Assuming what dictis yours Dictionary<User,bool>:

var conv = from kvp in dict
            select new UserDto
                    {
                        Avatar = kvp.Key.Avatar,
                        IsFriend = kvp.Value,
                        Username = kvp.Key.Username
                    };
-1
source

All Articles