c# - Automapper 根据源类型中的枚举值解析目标类型

标签 c# .net automapper

我正在尝试找到一种方法,让 Automapper 根据在源类型中设置的枚举值来选择映射调用的目标类型...

例如给定以下类:

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

现在,我想将其映射到具有以下类的 View 模型表示:

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 来支持它?这可能吗? (我希望这个问题很清楚)

谢谢!

最佳答案

好吧,我现在在想实现这样的事情的最好方法是使用 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};
        }

    }
}

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

关于c# - Automapper 根据源类型中的枚举值解析目标类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12604596/

相关文章:

带有 XML 结构化数据的 C# HttpWebRequest

c# - 如何解决此 System.IO.FileNotFoundException

在 BeforeMap/AfterMap 中使用 Map 方法进行 AutoMapper(非静态)配置

c# - 使用泛型方法避免递归来设置类属性c#

c# - 如何为 PathGeometry 设置动画以使其缓慢显示?

c# - 阅读 IMDB 电影列表的最有效方式

c# - 如何解决有关将 Moq 与 IDataReader 一起使用的问题

c# - Automapper - 如何从源子对象映射到目标

javascript - AngularJS 在 Xamarin Android Webview 中不工作

c# - Windows 服务结束后,Quartz.net 作业似乎仍然存在