![](/img/trans.png)
[英]How to use automapper to map Parent of source type into a collection of destination type?
[英]Automapper resolve destination type based on the value of an enum in source type
我試圖找到一種方法讓Automapper根據Source類型中設置的Enum值選擇映射調用的目標類型...
例如,給出以下類:
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 }
}
}
現在,我想將它映射到具有類的viewmodel表示:
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的調用將導致OrganisationViewModel包含一個NumericMetric和一個TextMetric。
Automapper呼叫:
var vm = Automapper.Map<Organisation, OrganisationViewModel>(Org);
我如何配置Automapper來支持這一點? 這可能嗎? (我希望這個問題很清楚)
謝謝!
好吧,我現在正在考慮實現這樣一個事情的最佳方法是使用TypeConverter作為度量標准部分...類似於:
AutoMapper.Mapper.Configuration
.CreateMap<Organisation, OrganisationViewModel>();
AutoMapper.Mapper.Configuration
.CreateMap<Metric, IMetricViewModels>()
.ConvertUsing<MetricTypeConverter>();
然后TypeConverter看起來像這樣:
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};
}
}
}
這看起來像是正確的方法嗎? 還有其他指導嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.