2012-09-26 41 views
8

我試圖找到一種方法讓Automapper根據源類型中設置的Enum值選擇映射調用的目標類型。 。Automapper根據源類型中枚舉的值解析目標類型

eg鑑於以下類:

public class Organisation 
{ 
    public string Name {get;set;} 
    public List<Metric> Metrics {get;set;} 
} 

public class Metric 
{ 
    public int NumericValue {get;set;} 
    public string TextValue {get;set;} 
    public MetricType MetricType {get;set;} 
} 

public enum MetricType 
{ 
    NumericMetric, 
    TextMetric 
} 

如果我有以下對象:

var Org = new Organisation { 
    Name = "MyOrganisation", 
    Metrics = new List<Metric>{ 
     new Metric { Type=MetricType.TextMetric, TextValue = "Very Good!" }, 
     new Metric { Type=MetricType.NumericMetric, NumericValue = 10 } 
    } 
} 

現在,我想這個映射到它的視圖模型表示它具有類:

public class OrganisationViewModel 
{ 
    public string Name {get;set;} 
    public List<IMetricViewModels> Metrics {get;set;} 
} 

public NumericMetric : IMetricViewModels 
{ 
    public int Value {get;set;} 
} 

public TextMetric : IMetricViewModels 
{ 
    public string Value {get;set;} 
} 

對AutoMapper.Map的調用將導致包含一個NumericMetric和一個TextMetric的OrganisationViewModel。

的Automapper電話:

var vm = Automapper.Map<Organisation, OrganisationViewModel>(Org); 

我怎麼會去配置Automapper支持呢?這可能嗎? (我希望這個問題很清楚)

謝謝!

+0

我一直在看這個,並繼續回到'公制'而不是兩種類型。例如,你如何同時使用'int Value'和'string Value'來實現IMetricViewModels。你的界面是什麼樣的? – hometoast

+0

嗨,這個例子比實際問題簡單得多,MetricType中有很多不同類型,都包含各種不同的東西。該界面是空的,只有在那裏讓我有一個事情的列表,這些列表將全部解析爲不同的視圖模板。 (MVC應用程序... Html.DisplayFor(Organisation.Metrics)將生成6或7個不同模板的列表)。這有道理嗎?還是我應該擴展這個問題? – Paul

回答

3

好吧,我想此刻要達到這樣的事情是與度量部分的TypeConverter,最好的辦法...喜歡的東西:

AutoMapper.Mapper.Configuration 
     .CreateMap<Organisation, OrganisationViewModel>(); 

AutoMapper.Mapper.Configuration 
     .CreateMap<Metric, IMetricViewModels>() 
     .ConvertUsing<MetricTypeConverter>(); 

然後類型轉換器會看起來像這:

public class MetricTypeConverter : AutoMapper.TypeConverter<Metric, IMetricViewModel> 
{ 
    protected override IMetricViewModelConvertCore(Metric source) 
    { 
     switch (source.MetricType) 
     { 
      case MetricType.NumericMetric : 
       return new NumericMetric {Value = source.NumericValue}; 

      case MetricType.TextMetric : 
       return new TextMetric {Value = source.StringValue}; 
     } 

    } 
} 

這似乎是正確的方法嗎?任何其他指導?

+0

你能夠得到這個工作?我似乎無法得到它的工作。 –