3

这是我的数据传输对象

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。

4

3 回答 3

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 配置,用于设置配置,即不匹配的字段等。

于 2013-06-12T13:53:24.100 回答
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
于 2013-06-12T14:48:17.237 回答
0

You could point it to the same IEnumerable:

ReportingEntity = data.ReportingEntity;

If you want to make a deep copy, you could use ToList(), or ToArray():

ReportingEntity = data.ReportingEntity.ToList();

That will materialize the IEnumerable and store a snapshot in your view model.

于 2013-06-12T13:55:34.100 回答