Search code examples
automapper-3

Automapper configuration for object


I have these classes

    public class NamedEntityViewModel
    {
        public string Name { get; set; }
    }

    public class NamedEntityListViewModel
    {
        public List<NamedEntityViewModel> List { get; set; }
    }
    public class Album : INamedEntity
    {
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        public virtual ICollection<Song> Songs { get; set; }
        [Required]
        public int AlbumNumber { get; set; }
    }

I have a List<Album> and I want to map that to NamedEntityListViewModel with NamedEntityViewModel.Name mapping to Album.Name. How do I set this up in Automapper?


Solution

  • Try something like that:

    First create you mapper:

    Mapper.CreateMap<Album, NamedEntityViewModel>();
    

    For the mapping do this:

    // yourAlbumList is a List<Album>
    var albumListVm = new NamedEntityListViewModel();
    albumListVm.List = Mapper.Map<IEnumerable<NamedEntityViewModel>>(yourAlbumList);
    

    This should do the job