将DTO转移到ViewModel

时间:2013-06-12 13:51:00

标签: 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; }
}

这是我的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; } 
}

}

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

3 个答案:

答案 0 :(得分: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);

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

答案 1 :(得分:1)

如果没有AutoMapper,您必须逐个映射每个属性,

这样的事情:

  LoadSourceDetail obj = FillLoadSourceDetail ();// fill from source or somewhere

     // check for null before
    ReportingEntity = obj.ReportingEntity
                     .Select(x => new ReportingEntityViewModel() 
                        { 
                           ReportingEntityCode  = x.ReportingEntityCode,
                           ReportingEntityDesc  x.ReportingEntityDesc
                         })
                     .ToList(); // here is  'x' is of type ReportingEntityDetail

答案 2 :(得分:0)

您可以将其指向相同的IEnumerable

ReportingEntity = data.ReportingEntity;

如果您想制作深层副本,可以使用ToList()ToArray()

ReportingEntity = data.ReportingEntity.ToList();

这将实现IEnumerable并在视图模型中存储快照。