Automapper 7.0.1-用于从List派生的类的通用TypeConverter

时间:2018-07-09 23:51:13

标签: asp.net-core .net-core automapper

public class PaginatedListConverter<TSource, TDestination> : ITypeConverter<PaginatedList<TSource>, PaginatedList<TDestination>>
{
    public PaginatedList<TDestination> Convert(PaginatedList<TSource> source, PaginatedList<TDestination> destination,
        ResolutionContext context)
    {
        if (destination == null)
        {
            destination = new PaginatedList<TDestination>();
        }
        foreach (var item in source)
        {
            var dest = context.Mapper.Map<TSource, TDestination>(item);
            destination.Add(dest);
        }
        destination.PageIndex = source.PageIndex;
        destination.TotalPages = source.TotalPages;

        return destination;
    }
}

public class PaginatedList<T> : List<T>
    {
        public int PageIndex { get; set; }
        public int TotalPages { get; set; }

    public PaginatedList()
    {

    }

    public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
    {
        PageIndex = pageIndex;
        TotalPages = (int)Math.Ceiling(count / (double)pageSize);

        this.AddRange(items);
    }

    public bool HasPreviousPage
    {
        get
        {
            return (PageIndex > 1);
        }
    }

    public bool HasNextPage
    {
        get
        {
            return (PageIndex < TotalPages);
        }
    }

    public static async Task<PaginatedList<T>> CreateAsync(
        IQueryable<T> source, int pageIndex, int pageSize)
    {
        var count = await source.CountAsync();
        var items = await source.Skip(
            (pageIndex - 1) * pageSize)
            .Take(pageSize).ToListAsync();
        return new PaginatedList<T>(items, count, pageIndex, pageSize);
    }
}

来源/目标类型

public class ActivityDTO
{
    public Guid ActivityId { get; set; }
    public string ActivityName { get; set; }
    public string ActivityDescription { get; set; }
    public ActivityStatus ActivityStatus { get; set; }
}

public class Activity
{
    public Activity()
    {
        Active = true;
    }

    public Guid ActivityId { get; set; }
    public string ActivityName { get; set; }
    public string ActivityDescription { get; set; }

    public virtual IEnumerable<Class> Classes { get; set; }
    public virtual ICollection<GymPlanXActivity> GymPlanXActivity { get; set; }

    public ActivityStatus ActivityStatus { get; set; }

    public bool Active { get; set; }
}

映射配置

CreateMap(typeof(PaginatedList<>), typeof(PaginatedList<>)).ConvertUsing(typeof(PaginatedListConverter<,>));

复制步骤

_mapper.Map<PaginatedList<ActivityDTO>>(activities);
//or 
_mapper.Map<PaginatedList<Activity>, PaginatedList<ActivityDTO>>(activities);

预期的行为 无需手动设置TotalPages和PageIndex属性即可进行转换

实际行为 1-如果未定义任何行为(CreateMap),它将仅忽略TotalPages和PageIndex属性 2-如果行为已定义(如上面的代码),则会引发一个简单错误,表明它无法转换(未提供更多详细信息)

参考号:https://github.com/AutoMapper/AutoMapper/issues/2712

0 个答案:

没有答案