使用Automapper按属性名称映射时的自定义处理值

时间:2017-02-21 08:46:00

标签: .net automapper

我使用以下属性名称将值与Automapper映射:

.ForMember(dstPropName, a => a.MapFrom(srcPropName));

有没有办法自定义处理从源获取的值?例如,我想修剪字符串。

我正在创建一个数据转换器,它应该接受非常不同的数据类型,并且调用者只提供列名(这是任务所必需的)。我不知道如何拦截获得的值并对它们做些什么。

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案!我需要IMemberValueResolver。

public class Source
{
    public string Text { get; set; }
    public string TextTime { get; set; }
}

public class Destination
{
    public string Message { get; set; }
    public DateTime? CreatedOn { get; set; }
}

public class DateTimeResolver : IMemberValueResolver<object, object, object, object>
{
    private readonly string _format;

    public DateTimeResolver(string format)
    {
        _format = format;
    }

    public object Resolve(object source, object destination, object sourceMember, object destMember, ResolutionContext context)
    {
        DateTime dt;
        return DateTime.TryParseExact(sourceMember.ToString(), _format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt) ? dt : (DateTime?) null;
    }
}

    private static void Main(string[] args)
    {

        Source src = new Source()
        {
            Text = "   message with spaces    ",
            TextTime = "04/22/1988"
        };

        DateTimeResolver dtReader = new DateTimeResolver("MM/dd/yyyy");

        Mapper.Initialize(cfg =>
            cfg.CreateMap(typeof (Source), typeof (Destination))
                // type resolver
                .ForMember("Message", opt => opt.ResolveUsing<TrimResolver, object>("Text"))
                // instance resolver
                .ForMember("CreatedOn", opt => opt.ResolveUsing(dtReader, "TextTime")));

        Destination dst =  Mapper.Map<Destination>(src);

    }
}