【问题标题】:Automapper resolve destination type based on the value of an enum in source typeAutomapper 根据源类型中的枚举值解析目标类型
【发布时间】:2012-09-26 14:55:27
【问题描述】:

我正在尝试找到一种方法,让 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 }
    }
}

现在,我想将其映射到具有类的视图模型表示:

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

谢谢!

【问题讨论】:

  • 我一直在看这个并一直回到Metric&lt;T&gt;而不是两种类型。例如,您如何让int Valuestring Value 都实现 IMetricViewModels。你的界面是什么样的?
  • 嗨,这个例子比实际问题简单得多,MetricType 中有很多不同的类型,都包含各种不同的东西。界面是空的,只有在那里允许我列出所有将解析为不同视图模板的事物列表。 (MVC 应用程序... Html.DisplayFor(Organisation.Metrics) 将产生 6 或 7 个不同模板的列表)。这有意义还是我应该扩大问题?

标签: c# .net automapper


【解决方案1】:

好的,我目前正在考虑实现这一目标的最佳方法是使用 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};
        }

    }
}

这似乎是正确的方法吗?还有其他指导吗?

【讨论】:

  • 你能让这个工作吗?我似乎无法让它工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
  • 1970-01-01
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
相关资源
最近更新 更多