将DTO转移到ViewModel

Ron*_*ald 3 c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

这是我的数据传输对象

public class LoadSourceDetail
{
  public string LoadSourceCode { get; set; }
  public string LoadSourceDesc { get; set; }
  public IEnumerable<ReportingEntityDetail> ReportingEntity { get; set; }
}

public class ReportingEntityDetail
{
  public string ReportingEntityCode { get; set; }
  public string ReportingEntityDesc { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这是我的ViewModel

public class LoadSourceViewModel
{
    #region Construction

        public LoadSourceViewModel ()
        {
        }

        public LoadSourceViewModel(LoadSourceDetail data)
        {
            if (data != null)
            {
                LoadSourceCode = data.LoadSourceCode;
                LoadSourceDesc = data.LoadSourceDesc;
                ReportingEntity = // <-- ?  not sure how to do this 
            };
        }


    #endregion
    public string LoadSourceCode { get; set; }  
    public string LoadSourceDesc { get; set; }
    public IEnumerable<ReportingEntityViewModel> ReportingEntity { get; set; }  
}

public class ReportingEntityViewModel 
{ 
    public string ReportingEntityCode { get; set; }
    public string ReportingEntityDesc { get; set; } 
}
Run Code Online (Sandbox Code Playgroud)

}

我不确定如何将数据从LoadSourceDetail ReportingEntity传输到LoadSourceViewModel ReportingEntity.我正在尝试将数据从一个IEnumerable传输到另一个IEnumerable.

hut*_*oid 6

我会使用AutoMapper来做到这一点:

https://github.com/AutoMapper/AutoMapper

http://automapper.org/

您可以轻松地映射集合,请参阅https://github.com/AutoMapper/AutoMapper/wiki/Lists-and-arrays

它看起来像这样:

var viewLoadSources = Mapper.Map<IEnumerable<LoadSourceDetail>, IEnumerable<LoadSourceViewModel>>(loadSources);
Run Code Online (Sandbox Code Playgroud)

如果你在MVC项目中使用它,我通常在App_Start中有一个AutoMapper配置来设置配置,即不匹配的字段等.