我試圖找到一種方法讓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支持呢?這可能嗎? (我希望這個問題很清楚)
謝謝!
我一直在看這個,並繼續回到'公制'而不是兩種類型。例如,你如何同時使用'int Value'和'string Value'來實現IMetricViewModels。你的界面是什麼樣的? –
hometoast
嗨,這個例子比實際問題簡單得多,MetricType中有很多不同類型,都包含各種不同的東西。該界面是空的,只有在那裏讓我有一個事情的列表,這些列表將全部解析爲不同的視圖模板。 (MVC應用程序... Html.DisplayFor(Organisation.Metrics)將生成6或7個不同模板的列表)。這有道理嗎?還是我應該擴展這個問題? – Paul