我試圖添加一個格式化程序到我的自動映射器配置中,以設置所有DateTime?
字段的樣式。我試着加入全球格式化我:自動映射器格式化程序不工作
Mapper.AddFormatter<DateStringFormatter>();
而且在特定的映射本身:
Mapper.CreateMap<Post, PostViewModel>()
.ForMember(dto => dto.Published, opt => opt.AddFormatter<DateStringFormatter>());
但無論似乎工作 - 它總是在輸出正常格式的日期。作爲參考,這裏是視圖模型我使用,和其餘配置:
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;
}
}
我在做什麼錯?
謝謝!
謝謝吉米,我選擇了第二種選擇。我有一些其他的源對象具有相同類型的字段。剛開始使用Automapper,並且非常喜歡它。 – leftend 2009-11-04 18:27:10
你有樣品嗎? – ntombela 2010-07-20 12:39:52