2011-11-25 164 views
0

我使用AutoMapper來映射我的域模型和視圖模型,反之亦然。使用AutoMapper映射兩個對象列表

我通常做我的映射像這樣在我的控制器:

// Mapping 
Tutorial tutorial = (Tutorial)tutorialMapper.Map(viewModel, typeof(TutorialEditViewModel), typeof(Tutorial)); 

我的教程映射器類來處理上面:

public class TutorialMapper : ITutorialMapper 
{ 
    static TutorialMapper() 
    { 
      Mapper.CreateMap<TutorialCreateViewModel, Tutorial>(); 
      Mapper.CreateMap<TutorialEditViewModel, Tutorial>(); 
      Mapper.CreateMap<Tutorial, TutorialEditViewModel>(); 
    } 

    public object Map(object source, Type sourceType, Type destinationType) 
    { 
      return Mapper.Map(source, sourceType, destinationType); 
    } 
} 

我試圖縮短我的列表之間的映射方式。我目前這樣做:

IEnumerable<Tutorial> tutorialsList = tutorialService.GetAll(); 
IEnumerable<TutorialListViewModel> tutorialListViewModels = 
    from t in tutorialsList 
    orderby t.Name 
    select new TutorialListViewModel 
    { 
      Id = t.Id, 
      Name = t.Name, 
      IsActive = t.IsActive 
    }; 

是否有可能映射它像這樣的東西?

我知道AutoMapper支持列表映射,但是如何將它實現到我的場景中呢?

我也試過如下:

IEnumerable<Tutorial> tutorialsList = tutorialService.GetAll(); 
IEnumerable<TutorialListViewModel> tutorialListViewModels = (IEnumerable<TutorialListViewModel>)tutorialMapper.Map(tutorialsList, typeof(IEnumerable<Tutorial>), typeof(IEnumerable<TutorialListViewModel>)); 

但如果在tutorialsList沒有項目,然後我得到以下錯誤:

{"The entity type Tutorial is not part of the model for the current context."} 

回答

-4

我從來沒有定義我的教程實體在我的上下文文件中設置。它現在有效。

+2

你能後的代碼,請? – Buzzer

+2

你可以發佈代碼否則這真的不是答案 – Peter

1

也許你可以嘗試這樣的事:

public ViewResult Index() 
    { 
     IList<City> cities = db.Cities.ToList(); 

     IList<CityViewModel> viewModelList = Mapper.Map<IList<City>, IList<CityViewModel>>(cities); 
     return View(viewModelList); 
    }