簡體   English   中英

Automapper map 可以分頁列表嗎?

[英]Can Automapper map a paged list?

我想 map 業務對象的分頁列表到視圖 model 對象的分頁列表,使用如下:

var listViewModel = _mappingEngine.Map<IPagedList<RequestForQuote>, IPagedList<RequestForQuoteViewModel>>(requestForQuotes);

分頁列表實現類似於 Rob Conery 在這里的實現: http://blog.wekeroad.com/2007/12/10/as.net-mvc-pagedlistt/

您如何設置 Automapper 來執行此操作?

使用jrummell的答案,我創建了一個與Troy Goode的PagedList一起使用的擴展方法。 它讓你不必在任何地方放置如此多的代碼......

    public static IPagedList<TDestination> ToMappedPagedList<TSource, TDestination>(this IPagedList<TSource> list)
    {
        IEnumerable<TDestination> sourceList = Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(list);
        IPagedList<TDestination> pagedResult = new StaticPagedList<TDestination>(sourceList, list.GetMetaData());
        return pagedResult;

    }

用法是:

var pagedDepartments = database.Departments.OrderBy(orderBy).ToPagedList(pageNumber, pageSize).ToMappedPagedList<Department, DepartmentViewModel>();

AutoMapper不支持開箱即用,因為它不知道IPagedList<>任何實現。 但是你有兩個選擇:

  1. 使用現有的Array / EnumerableMappers作為指南編寫自定義IObjectMapper 這是我親自去的方式。

  2. 編寫自定義TypeConverter,使用:

     Mapper .CreateMap<IPagedList<Foo>, IPagedList<Bar>>() .ConvertUsing<MyCustomTypeConverter>(); 

    並在里面使用Mapper.Map來映射列表的每個元素。

如果你正在使用Troy Goode的 StaticPagedList ,那么有一個StaticPagedList類可以幫助你映射。

// get your original paged list
IPagedList<Foo> pagedFoos = _repository.GetFoos(pageNumber, pageSize);
// map to IEnumerable
IEnumerable<Bar> bars = Mapper.Map<IEnumerable<Bar>>(pagedFoos);
// create an instance of StaticPagedList with the mapped IEnumerable and original IPagedList metadata
IPagedList<Bar> pagedBars = new StaticPagedList<Bar>(bars, pagedFoos.GetMetaData());

我在AutoMapper周圍創建了一個小包裝器,將PagedList<DomainModel>映射到PagedList<ViewModel>

public class MappingService : IMappingService
{
    public static Func<object, Type, Type, object> AutoMap = (a, b, c) =>
    {
        throw new InvalidOperationException(
            "The Mapping function must be set on the MappingService class");
    };

    public PagedList<TDestinationElement> MapToViewModelPagedList<TSourceElement, TDestinationElement>(PagedList<TSourceElement> model)
    {
        var mappedList = MapPagedListElements<TSourceElement, TDestinationElement>(model);
        var index = model.PagerInfo.PageIndex;
        var pageSize = model.PagerInfo.PageSize;
        var totalCount = model.PagerInfo.TotalCount;

        return new PagedList<TDestinationElement>(mappedList, index, pageSize, totalCount);
    }

    public object Map<TSource, TDestination>(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<object> input = ((IEnumerable)source).OfType<object>();
            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<TDestinationElement> MapPagedListElements<TSourceElement, TDestinationElement>(IEnumerable<TSourceElement> model)
    {
        return model.Select(element => AutoMap(element, typeof(TSourceElement), typeof(TDestinationElement))).OfType<TDestinationElement>();
    }
}

用法:

PagedList<Article> pagedlist = repository.GetPagedList(page, pageSize);
mappingService.MapToViewModelPagedList<Article, ArticleViewModel>(pagedList);

重要的是你必須使用元素類型!

如果您有任何問題或建議,請隨時評論:)

AutoMapper自動處理幾種類型的列表和數組之間的轉換: http ://automapper.codeplex.com/wikipage?title = List%20and%20Arrays

它似乎不會自動轉換從IList繼承的自定義類型的列表,但解決方法可能是:

    var pagedListOfRequestForQuote = new PagedList<RequestForQuoteViewModel>(
        AutoMapper.Mapper.Map<List<RequestForQuote>, List<RequestForQuoteViewModel>>(((List<RequestForQuote>)requestForQuotes),
        page ?? 1,
        pageSize

我需要使用支持ASP.NET Web API的IMapper接口的AutoMapper版本6.0.2返回可序列化版本的IPagedList<> 那么,如果問題是我如何支持以下內容:

//Mapping from an enumerable of "foo" to a different enumerable of "bar"...
var listViewModel = _mappingEngine.Map<IPagedList<RequestForQuote>, PagedViewModel<RequestForQuoteViewModel>>(requestForQuotes);

然后人們可以這樣做:

定義PagedViewModel<T>
來源: AutoMapper自定義類型轉換器無法正常工作

public class PagedViewModel<T>
{
    public int FirstItemOnPage { get; set; }
    public bool HasNextPage { get; set; }
    public bool HasPreviousPage { get; set; }
    public bool IsFirstPage { get; set; }
    public bool IsLastPage { get; set; }
    public int LastItemOnPage { get; set; }
    public int PageCount { get; set; }
    public int PageNumber { get; set; }
    public int PageSize { get; set; }
    public int TotalItemCount { get; set; }
    public IEnumerable<T> Subset { get; set; }
}

將開放式通用轉換器從IPagedList<T>寫入PagedViewModel<T>
資料來源: https//github.com/AutoMapper/AutoMapper/wiki/Open-Generics

public class Converter<TSource, TDestination> : ITypeConverter<IPagedList<TSource>, PagedViewModel<TDestination>>
{
    public PagedViewModel<TDestination> Convert(IPagedList<TSource> source, PagedViewModel<TDestination> destination, ResolutionContext context)
    {
        return new PagedViewModel<TDestination>()
        {
            FirstItemOnPage = source.FirstItemOnPage,
            HasNextPage = source.HasNextPage,
            HasPreviousPage = source.HasPreviousPage,
            IsFirstPage = source.IsFirstPage,
            IsLastPage = source.IsLastPage,
            LastItemOnPage = source.LastItemOnPage,
            PageCount = source.PageCount,
            PageNumber = source.PageNumber,
            PageSize = source.PageSize,
            TotalItemCount = source.TotalItemCount,
            Subset = context.Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>(source) //User mapper to go from "foo" to "bar"
        };
    }
}

配置映射器

new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<RequestForQuote, RequestForQuoteViewModel>();//Define each object you need to map
        cfg.CreateMap(typeof(IPagedList<>), typeof(PagedViewModel<>)).ConvertUsing(typeof(Converter<,>)); //Define open generic mapping
    });

Automapper .net core 8.1.1 很容易

您只需要將類型映射添加到您的 mapperProfile 並映射 pagedList 內的對象

CreateMap(typeof(IPagedList<>), typeof(IPagedList<>));
CreateMap<RequestForQuote, RequestForQuoteViewModel>().ReverseMap();

並且您可以直接在 mapper.Map 中使用它 - 在類構造函數中從 IMapper 初始化映射器

RequestForQuote result
_mapper.Map<IPagedList<RequestForQuoteViewModel>>(result);

如果您正在使用 X.PageList 那么您可以簡單地使用此代碼:

PagedList<exampleDTO> result = new PagedList<exampleDTO>(item, _mapper.Map<List<exampleDTO>>(item.ToList()));

PageList 允許您使用修改后的項目創建新的 PageList。

更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM