Automapper 構成にフォーマッターを追加して、すべてのDateTime?
フィールドのスタイルを設定しようとしています。フォーマッターをグローバルに追加しようとしました:
Mapper.AddFormatter<DateStringFormatter>();
そして、特定のマッピング自体について:
Mapper.CreateMap<Post, PostViewModel>()
.ForMember(dto => dto.Published, opt => opt.AddFormatter<DateStringFormatter>());
しかし、どちらも機能していないようです-常に通常の形式で日付を出力します。参考までに、私が使用している ViewModel と残りの構成を次に示します。
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;
}
}
私は何を間違っていますか?
ありがとう!