2013-06-12 4 views
3

Вот моя передача данных объектапередача DTO в ViewModel

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.

ответ

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 я обычно имеют AutoMapper конфигурации в App_Start, который устанавливает т.е. конфигурации полей, которые не соответствуют друг другу и т.д.

+0

Я использую automapper для всех моих отображений и из ViewModels –

+0

спасибо за предложение, но я «Мне нравится знать, как это сделать« вручную »без AutoMapper. –

+0

Нет проблем, для меня это был бы старомодный DTO с методом To() и From(). Я оставлю свой ответ там, так как сейчас я это сделаю. – hutchonoid

0

Вы могли бы указать на тот же IEnumerable:

ReportingEntity = data.ReportingEntity; 

Если вы хотите сделать глубокую копию, вы можете использовать ToList() или ToArray():

ReportingEntity = data.ReportingEntity.ToList(); 

Это будет материализовать IEnumerable и сохранить снимок в вашей модели представления.

+0

Я получаю сообщение об ошибке «Невозможно неявно преобразовать тип» System.Collections.Generic.IEnumerable 'to' System.Collections.Generic.IEnumerable '. Явное преобразование существует (вам не хватает роли?) " –