0

我怎样才能转换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

4

2 回答 2

1

属性名称应该匹配,或者您必须覆盖Id. 您还必须明确IgnoreCreationTime

AutoMapper.Mapper.CreateMap<Category, CategoryViewModel>()
.ForMember(x => x.CategoryId, src => src.MapFrom(y => y.Id))
.ForSourceMember(x => x.CreationTime, y => y.Ignore());
于 2013-05-09T18:15:36.303 回答
0

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

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

public class CategoryViewModel
{
    public Guid  CategoryId { get; set; }
    public string Name { get; set; }
}
于 2013-05-09T18:12:13.157 回答