为什么这样做
Mapper.CreateMap<MyObject, AnotherObject>().
ForMember(x => x.DateAsString, m => m.ResolveUsing<StringToDateTimeFormatter>());
private class StringToDateTimeFormatter : ValueResolver<DateTime, string>
{
protected override string ResolveCore(DateTimesource)
{
return source.ToString("yyyy-MM-dd");
}
}
何时可以这样做
Mapper.CreateMap<MyObject, AnotherObject>().
ForMember(x => x.DateAsString, m => m.MapFrom(x => x.Date.ToString("yyy-MM-dd")));
???
更新
以下是如何执行更复杂的业务逻辑的示例
Mapper.CreateMap<MyObject, AnotherObject>().
ForMember(x => x.DateAsString, m => m.MapFrom(n => MyMethod(n.DateAsString)));
private object MyMethod(string dateTime)
{
if(!MyDomainObjectIsValid(dateTime))
{
throw new MyValidationException();
}
// do more stuff
}
我仍然认为不需要ValueResolver ......
答案 0 :(得分:4)
显然,对于您的示例,仅使用MapFrom
更合理。
更复杂的情况需要ValueResolvers。例如,当您需要进行一些验证并相应地抛出异常时。
修改强> ValueResolvers提供对目标类型和值的访问。这是一个小例子。
public class FakeResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
if (source.Context.DestinationType == typeof(string) && source.Context.DestinationValue == "test")
throw new Exception();
return source;
}
}