【问题标题】:How to map a viewModel to a hierarchy model with arrays with AutoMapper?如何使用 AutoMapper 将 viewModel 映射到具有数组的层次模型?
【发布时间】:2011-08-10 08:42:34
【问题描述】:

深度模型是由大量数组(想想基于 wsdl 的 WCF 代理生成的代码)代码生成的,需要用扁平化的视图模型填充。两种模型之间没有命名约定。

平面模型如下所示:

public class ViewModel
{
    public string Item1 { get; set; }
    public string Item2 { get; set; }
}

深度模型如下所示:

public class DeepLevel0
{
    public DeepLevel1 Level1 { get; set; }
}

public class DeepLevel1
{
    public string Prop1;
    public DeepLevel2[] Level2 { get; set; }
}

public class DeepLevel2
{
    public string Prop2;
    public string Prop3;
}

最终的映射结果应该如下

DeepLevel0.Level1.Prop1 = ViewModel.Item1
DeepLevel0.Level1.Level2[0].Prop2 = ViewModel.Item2
DeepLevel0.Level1.Level2[0].Prop2 = null;

我真的很喜欢 AutoMapper 中的验证系统,因为我知道您处理了所有属性。

我得到了以下工作(但失去了验证):

  Mapper.CreateMap<ViewModel, DeepLevel0>()
      .ForMember(d => d.Level1, opt => opt.MapFrom(s => 
          new DeepLevel1 {
                            Prop1 = s.Item1,
                            Level2 = new[]
                                        {
                                            new DeepLevel2
                                                {
                                                    Prop2 = s.Item2,
                                                    Prop3 = null
                                                }
                                        }
                        }));
    }

还有其他更好的方法吗?

【问题讨论】:

    标签: c# arrays mapping automapper asp.net-mvc


    【解决方案1】:

    不,我不这么认为。你总是可以切换到对 DeepLevel 对象使用构造函数,这可能会稍微整理一下它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多