Automapper: Target TypeConverter to specific objects
I'm using Automapper to convert one object to another like this:
Mapper.Initialize(cfg =>
{
cfg.RecognizePrefixes("m_n", "m_b", "m_l", "m_ach", "m_wz", "m_sz");
cfg.CreateMap<short[], string>().ConvertUsing(new ShortArrayTypeConverter());
cfg.CreateMap<int, DateTime>().ConvertUsing(new DateTimeTypeConverter());
cfg.CreateMap<SUserInfoApiV4, UserInfo>();
});
Mapper.AssertConfigurationIsValid();
This works great when I want to map SUserInfoApiV4 into UserInfo. However, I also need to convert other objects and even do the reverse (like UserInfo into SUserInfoApiV4).
This is where I run into issues. The type converters are global and not tied to a specific object. I tried to solve this by using profiles like so:
Mapper.Initialize(cfg =>
{
cfg.CreateMap<SUserInfoApiV4, UserInfo>();
cfg.AddProfile<SUserInfoApiV4Profile>();
cfg.CreateMap<UserInfo, SUserInfoApiV4> ();
cfg.AddProfile<UserInfoProfile>();
});
Mapper.AssertConfigurationIsValid();
And then add the following profiles:
public class SUserInfoApiV4Profile : Profile
{
public SUserInfoApiV4Profile()
{
CreateMap<short[], string>().ConvertUsing(new ShortArrayTypeConverter());
CreateMap<int, DateTime>().ConvertUsing(new IntDateTimeTypeConverter());
}
}
public class UserInfoProfile : Profile
{
public UserInfoProfile()
{
CreateMap<string, short[]>().ConvertUsing(new StringTypeConverter());
CreateMap<DateTime, int>().ConvertUsing(new DateTimeIntTypeConverter());
}
}
However, it doesn't seem to work as intended (or as I thought). Is there a way to associate the type converters to specific objects so I don't have to convert every member manually?
Edit: I found this topic after a while: Customer value resolver with automapper global but only for a specific map?
So I guess it's not possible and I have to manually map every field. Now I don't understand the reason why I should use AutoMapper in the first place.
链接地址: http://www.djcxy.com/p/37362.html上一篇: 具有动态目标属性的AutoMapper