使用automapper映射复杂对象

时间:2013-05-09 18:08:19

标签: c# automapper

如何使用此定义将IEnumerable<Category>转换为IEnumerable<CategoryViewModel>

public class Category
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public DateTime CreationTime { get; set; }

    }

public class CategoryViewModel
{
    public Guid  CategoryId { get; set; }
    public string Name { get; set; }
}

我这样做了

public static IEnumerable<CategoryViewModel> ConvertToCategoryViewModelList(this IEnumerable<Category> category)
        {
            return Mapper.Map<IEnumerable<Category>, IEnumerable<CategoryViewModel>>(category);

但它没有将Id映射到CategoryId,我也不希望在CategoryVeiwModel中有CreationTime

2 个答案:

答案 0 :(得分:1)

要么属性名称匹配,要么必须覆盖Id的映射。此外,您必须明确Ignore CreationTime

AutoMapper.Mapper.CreateMap<Category, CategoryViewModel>()
.ForMember(x => x.CategoryId, src => src.MapFrom(y => y.Id))
.ForSourceMember(x => x.CreationTime, y => y.Ignore());

答案 1 :(得分:0)

我认为你可以使用继承和向下转换(或者是向上转换)

public class Category : CategoryViewModel
{
    public DateTime CreationTime { get; set; }
}

public class CategoryViewModel
{
    public Guid  CategoryId { get; set; }
    public string Name { get; set; }
}