对象的自动映射配置

时间:2014-02-09 23:00:57

标签: automapper-3

我有这些课程

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

我有List<Album>,我希望将其映射到NamedEntityListViewModelNamedEntityViewModel.Name映射到Album.Name。如何在Automapper中进行设置?

1 个答案:

答案 0 :(得分:1)

尝试类似的东西:

首先创建mapper:

Mapper.CreateMap<Album, NamedEntityViewModel>();

对于映射,请执行以下操作:

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

这应该做的工作