简体   繁体   中英

Using AutoMapper to map between 2 lists of objects

I use AutoMapper to map between my domain model and view model and vice versa.

I normally do my mappings like this in my controller:

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

My tutorial mapper class to handle the above:

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);
     }
}

I'm trying to shorten my way of mapping between lists. I currently do it like this:

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
     };

Is it possible to map it soemthing like this?

I know that AutoMapper supports mapping of lists, but how would I implement it into my scenario?

I also tried the following:

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

But if there are no items in tutorialsList then I get the following error:

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

Maybe you could try something like this:

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

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

I never defined my Tutorial entity set in my context file. It works now.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM