[英]Using AutoMapper to map between 2 lists of objects
我使用AutoMapper
在域模型和視圖模型之間進行映射,反之亦然。
我通常在控制器中像這樣進行映射:
// Mapping
Tutorial tutorial = (Tutorial)tutorialMapper.Map(viewModel, typeof(TutorialEditViewModel), typeof(Tutorial));
我的教程mapper類可以處理上述問題:
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."}
也許您可以嘗試這樣的事情:
public ViewResult Index()
{
IList<City> cities = db.Cities.ToList();
IList<CityViewModel> viewModelList = Mapper.Map<IList<City>, IList<CityViewModel>>(cities);
return View(viewModelList);
}
我從未在上下文文件中定義我的Tutorial實體集。 現在可以使用了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.