I'm trying to add a formatter to my Automapper configuration to style all DateTime?
fields. I've tried adding my formatter globally:
Mapper.AddFormatter<DateStringFormatter>();
And on the specific mapping itself:
Mapper.CreateMap<Post, PostViewModel>()
.ForMember(dto => dto.Published, opt => opt.AddFormatter<DateStringFormatter>());
But neither seems to work - it always outputs the date in the normal format. For reference, here is the ViewModel I'm using, and the rest of the configuration:
public class DateStringFormatter : BaseFormatter<DateTime?>
{
protected override string FormatValueCore(DateTime? value)
{
return value.Value.ToString("d");
}
}
public abstract class BaseFormatter<T> : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
if (context.SourceValue == null)
return null;
if (!(context.SourceValue is T))
return context.SourceValue == null ? String.Empty : context.SourceValue.ToString();
return FormatValueCore((T)context.SourceValue);
}
protected abstract string FormatValueCore(T value);
}
PostViewModel:
public int PostID { get; set; }
public int BlogID { get; set; }
public string UniqueUrl { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string BodyShort { get; set; }
public string ViewCount { get; set; }
public DateTime CreatedOn { get; set; }
private DateTime? published;
public DateTime? Published
{
get
{
return (published.HasValue) ? published.Value : CreatedOn;
}
set
{
published = value;
}
}
What am I doing wrong?
Thanks!