2013-06-12 36 views
3

这里是我的数据传输对象传递DTO,将视图模型

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

​​

}

我不知道如何将数据从LoadSourceDetail转移ReportingEntity到LoadSourceViewModel ReportingEntity。我试图从一个IEnumerable传输数据到另一个IEnumerable。

回答

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

+0

我用automapper为我所有的映射和​​的ViewModels –

+0

感谢您的建议,但我'想知道如何在没有AutoMapper的情况下手动执行此操作。 –

+0

没问题,对我来说这将是一个带有To()和From()方法的老式DTO。我会在那里留下我的答案,因为这是我现在要做的方式。 – hutchonoid

0

你可以将它指向同一IEnumerable

ReportingEntity = data.ReportingEntity; 

如果你想使一个深拷贝,你可以使用ToList(),或ToArray()

ReportingEntity = data.ReportingEntity.ToList(); 

这将兑现的IEnumerable并存储在您的视图模型的快照。

+0

我得到一个错误“无法隐式转换类型‘System.Collections.Generic.IEnumerable ’到“System.Collections.Generic.IEnumerable ”。一个显式转换存在(是否缺少强制转换?)” –