2009-10-30 41 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