Can Automapper map a paged list?

前端 未结 6 1901
我寻月下人不归
我寻月下人不归 2021-02-01 19:38

I\'d like to map a paged list of business objects to a paged list of view model objects using something like this:

var listViewModel = _mappingEngine.Map

        
6条回答
  •  情歌与酒
    2021-02-01 20:02

    I created a little wrapper around AutoMapper to map PagedList to PagedList.

    public class MappingService : IMappingService
    {
        public static Func AutoMap = (a, b, c) =>
        {
            throw new InvalidOperationException(
                "The Mapping function must be set on the MappingService class");
        };
    
        public PagedList MapToViewModelPagedList(PagedList model)
        {
            var mappedList = MapPagedListElements(model);
            var index = model.PagerInfo.PageIndex;
            var pageSize = model.PagerInfo.PageSize;
            var totalCount = model.PagerInfo.TotalCount;
    
            return new PagedList(mappedList, index, pageSize, totalCount);
        }
    
        public object Map(TSource model)
        {
            return AutoMap(model, typeof(TSource), typeof(TDestination));
        }
    
        public object Map(object source, Type sourceType, Type destinationType)
        {
            if (source is IPagedList)
            {
                throw new NotSupportedException(
                    "Parameter source of type IPagedList is not supported. Please use MapToViewModelPagedList instead");
            }
    
            if (source is IEnumerable)
            {
                IEnumerable input = ((IEnumerable)source).OfType();
                Array a = Array.CreateInstance(destinationType.GetElementType(), input.Count());
    
                int index = 0;
                foreach (object data in input)
                {
                    a.SetValue(AutoMap(data, data.GetType(), destinationType.GetElementType()), index);
                    index++;
                }
                return a;
            }
    
            return AutoMap(source, sourceType, destinationType);
        }
    
        private static IEnumerable MapPagedListElements(IEnumerable model)
        {
            return model.Select(element => AutoMap(element, typeof(TSourceElement), typeof(TDestinationElement))).OfType();
        }
    }
    
    
    

    Usage:

    PagedList
    pagedlist = repository.GetPagedList(page, pageSize); mappingService.MapToViewModelPagedList(pagedList);

    It is important that you would have to use the element types!

    If you have any question or suggestions, please feel free to comment :)

    提交回复
    热议问题