2011-11-25 98 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); 
    }