AutoMapper : Site wide usage of IValueFormatter for given types
Posted
by CRice
on Stack Overflow
See other posts from Stack Overflow
or by CRice
Published on 2010-05-06T06:53:43Z
Indexed on
2010/05/06
6:58 UTC
Read the original article
Hit count: 211
It is my understanding I can configure AutoMapper in the following way and during mapping it should format all source model dates to the rules defined in the IValueFormatter and set the result to the mapped model.
ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();
ForSourceType<DateTime?>().AddFormatter<StandardDateFormatter>();
I get no effect for my mapped class with this. It only works when I do the following:
Mapper.CreateMap<Member, MemberForm>().ForMember(x => x.DateOfBirth, y => y.AddFormatter<StandardDateFormatter>());
I am mapping DateTime? Member.DateOfBirth to string MemberForm.DateOfBirth. The formatter basically creates a short date string from the date.
Is there something I am missing when setting the default formatter for a given type?
Thanks
public class StandardDateFormatter : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
if (context.SourceValue == null)
return null;
if (!(context.SourceValue is DateTime))
return context.SourceValue.ToNullSafeString();
return ((DateTime)context.SourceValue).ToShortDateString();
}
}
© Stack Overflow or respective owner