2009-10-30 18 views
2

我试图添加一个格式化程序到我的自动映射器配置中,以设置所有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; 
     } 
    } 

我在做什么错?

谢谢!

回答

7

格式化程序仅适用于目标成员类型为“string”类型的情况。由于“发布”类型是“DateTime?”,因此格式化程序从未得到应用。你有几个选择这里:

  • 已发布的属性添加到对象后,上面
  • 创建已发布属性自定义解析中规定的行为,这首先解决了日期时间?来自属性逻辑的​​值,然后将目标成员类型更改为已发布的字符串。首先,解析器将执行。接下来,格式化需要自定义冲突解决的结果,最后,得到的值设置上发布
  • 做所有的自定义类型 - >字符串格式化的视图,用的东西像的HtmlHelper

我们通常会去1),除非显示的值只是为了这个视图,然后我们去选项2)。

+0

谢谢吉米,我选择了第二种选择。我有一些其他的源对象具有相同类型的字段。刚开始使用Automapper,并且非常喜欢它。 – leftend 2009-11-04 18:27:10

+0

你有样品吗? – ntombela 2010-07-20 12:39:52

0

尝试做这种方式:

Mapper.CreateMap<DateTime?, string>().ConvertUsing(d => d.Value.ToString("d")); 

您可以更改功能,满足您的要求。

+0

这似乎并不奏效......每当我写出我的“已发布”字段......它将以相同格式写出日期:MM/DD/YYYY HH:MM:SS PM It似乎并不像AutoMapper正在影响该字段......使用“ConvertUsing”或自定义格式化程序。 – leftend 2009-10-31 23:46:18