自动映射器根据源类型中枚举的值解析目标类型

Pau*_*aul 10 .net c# automapper

我试图找到一种方法让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
}
Run Code Online (Sandbox Code Playgroud)

如果我有以下对象:

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 }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我想将它映射到具有类的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;}
}
Run Code Online (Sandbox Code Playgroud)

对AutoMapper.Map的调用将导致OrganisationViewModel包含一个NumericMetric和一个TextMetric.

Automapper呼叫:

var vm = Automapper.Map<Organisation, OrganisationViewModel>(Org);
Run Code Online (Sandbox Code Playgroud)

我如何配置Automapper来支持这一点?这可能吗?(我希望这个问题很清楚)

谢谢!

Pau*_*aul 2

好吧,我现在想实现这样的事情的最佳方法是使用 TypeConverter 来表示公制部分......类似于:

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

AutoMapper.Mapper.Configuration
        .CreateMap<Metric, IMetricViewModels>()
        .ConvertUsing<MetricTypeConverter>();
Run Code Online (Sandbox Code Playgroud)

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

    }
}
Run Code Online (Sandbox Code Playgroud)

这看起来是正确的方法吗?还有其他指导吗?