我正试图找到一种方法让Automapper根据Source类型中设置的Enum值选择要映射的目标类型...
e.g。鉴于以下类别:
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的调用将导致OrganisationViewModel包含一个NumericMetric和一个TextMetric。
Automapper呼叫:
var vm = Automapper.Map<Organisation, OrganisationViewModel>(Org);
我如何配置Automapper来支持此功能?这可能吗? (我希望这个问题很清楚)
谢谢!
答案 0 :(得分:3)
好的,我现在正在考虑实现此类事情的最佳方法是使用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};
}
}
}
这看起来像是正确的方法吗?还有其他指导吗?