Automapper resolves destination type based on enumeration value in source type

I'm trying to find a way for Automapper to select a call destination type for matching based on the Enum value given in the source type ...

eg. Given the following classes:

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 } 

If I have the following object:

 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 } } } 

Now I want to map this to a view of a view that has classes:

 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;} } 

When you call AutoMapper.Map, an OrganizationViewModel will be created containing one NumericMetric and one TextMetric.

Automapper call:

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

How do I configure Automapper to support this? Is it possible? (Hope this question is clear)

Thanks!

+8
c # automapper
source share
1 answer

Well, I think that at the moment, the best way to achieve such a thing would be with TypeConverter for the metric part ... Something like:

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

Then TypeConverter will look something like this:

 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}; } } } 

Does this sound like the right approach here? Any other recommendations?

+3
source share

All Articles