问题描述

系统中实现了一个自定义的PagedList

/// <summary>
/// Paged list interface
/// </summary>
public interface IPagedList
{
int PageIndex { get; }
int PageSize { get; }
int TotalCount { get; }
int TotalPages { get; }
bool HasPreviousPage { get; }
bool HasNextPage { get; }
} /// <summary>
/// Paged list interface
/// </summary>
public interface IPagedList<T> : IList<T>, IPagedList
{
} /// <summary>
/// Paged list
/// </summary>
/// <typeparam name="T">T</typeparam>
[Serializable]
public class PagedList<T> : List<T>, IPagedList<T>
{
/// <summary>
/// Ctor
/// </summary>
/// <param name="source">source</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
public PagedList(IQueryable<T> source, int pageIndex, int pageSize)
{
int total = source.Count();
this.TotalCount = total;
this.TotalPages = total / pageSize; if (total % pageSize > 0)
TotalPages++; this.PageSize = pageSize;
this.PageIndex = pageIndex;
this.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
} /// <summary>
/// Ctor
/// </summary>
/// <param name="source">source</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
public PagedList(IList<T> source, int pageIndex, int pageSize)
{
TotalCount = source.Count();
TotalPages = TotalCount / pageSize; if (TotalCount % pageSize > 0)
TotalPages++; this.PageSize = pageSize;
this.PageIndex = pageIndex;
this.AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
} /// <summary>
/// Ctor
/// </summary>
/// <param name="source">source</param>
/// <param name="pageIndex">Page index</param>
/// <param name="pageSize">Page size</param>
/// <param name="totalCount">Total count</param>
public PagedList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
{
TotalCount = totalCount;
TotalPages = TotalCount / pageSize; if (TotalCount % pageSize > 0)
TotalPages++; this.PageSize = pageSize;
this.PageIndex = pageIndex;
this.AddRange(source);
} public int PageIndex { get; private set; }
public int PageSize { get; private set; }
public int TotalCount { get; private set; }
public int TotalPages { get; private set; } public bool HasPreviousPage
{
get { return (PageIndex > 0); }
}
public bool HasNextPage
{
get { return (PageIndex + 1 < TotalPages); }
}
}

转换失败,AutoMapper可不认识PagedList

 [TestMethod]
public void MapTest2()
{
Mapper.CreateMap<User, UserViewModel>(); var userList = new List<User>()
{
new User() {Name = "Name1", UserId = "UserId1"},
new User() {Name = "Name2", UserId = "UserId2"},
new User() {Name = "Name3", UserId = "UserId3"},
new User() {Name = "Name4", UserId = "UserId4"},
new User() {Name = "Name5", UserId = "UserId5"},
new User() {Name = "Name6", UserId = "UserId6"},
new User() {Name = "Name7", UserId = "UserId7"},
}; var pagedList = new PagedList<User>(userList, 0, 5); Mapper.Map<PagedList<User>, PagedList<UserViewModel>>(pagedList);//Exception }

解决方案

 /// <summary>
/// The collection extensions.
/// </summary>
public static class ObjectExtensions
{
private static readonly MethodInfo mapMethod;
private static readonly ConcurrentDictionary<Tuple<Type, Type>, Tuple<MethodInfo, Type>> methodsMapper = new ConcurrentDictionary<Tuple<Type, Type>, Tuple<MethodInfo, Type>>(); static ObjectExtensions()
{
mapMethod = (typeof(Mapper)).GetMethods().FirstOrDefault(_ => _.Name == "Map" && _.GetParameters().Length == 1);
} public static T MapTo<T>(this IPagedList tList) where T : class
{
var totalCount = tList.TotalCount;
var pageIndex = tList.PageIndex;
var pageSize = tList.PageSize; var t = methodsMapper.GetOrAdd(new Tuple<Type, Type>(tList.GetType(), typeof(T)), _ =>
{
var targetGenericArguments = typeof(T).GenericTypeArguments[0];
var targetGenericArgumentsIEnumerableType = typeof(IEnumerable<>).MakeGenericType(targetGenericArguments);
return new Tuple<MethodInfo, Type>(mapMethod.MakeGenericMethod(targetGenericArgumentsIEnumerableType),
typeof(PagedList<>).MakeGenericType(targetGenericArguments));
});
var rtn2 = t.Item1.Invoke(null, new object[] { tList });
var o2 = Activator.CreateInstance(t.Item2, rtn2, pageIndex, pageSize, totalCount) as T;
return o2;
} public static T MapTo<T>(this object o) where T : class
{
//way1
//var mapMethod = (typeof(Mapper)).GetMethods().FirstOrDefault(_ => _.Name == "Map" && _.GetParameters().Length == 1 && _.GetGenericArguments().Length == 2 );
//var m2 = mapMethod.MakeGenericMethod(o.GetType(), typeof (T));
//return m2.Invoke(null, new[] { o }) as T; //way2
return Mapper.Map<T>(o);
} public static void MapTo<S,T>(this S o,T t) where T : class
{
Mapper.Map(o,t);
}
}

测试通过

[TestMethod]
public void MapTest2()
{
Mapper.CreateMap<User, UserViewModel>(); var userList = new List<User>()
{
new User() {Name = "Name1", UserId = "UserId1"},
new User() {Name = "Name2", UserId = "UserId2"},
new User() {Name = "Name3", UserId = "UserId3"},
new User() {Name = "Name4", UserId = "UserId4"},
new User() {Name = "Name5", UserId = "UserId5"},
new User() {Name = "Name6", UserId = "UserId6"},
new User() {Name = "Name7", UserId = "UserId7"},
}; var pagedList = new PagedList<User>(userList, 0, 5);
var vmPagedList = pagedList.MapTo<PagedList<UserViewModel>>();
Assert.IsTrue(vmPagedList.TotalPages == 2
&& vmPagedList.PageSize == 5
&& vmPagedList.PageIndex == 0
); }

总结

运行时动态获取泛型参数并执行Mapper.Map<IEnumerable<TSource>, IEnumerable<TDestination>>,并且使用ConcurrentDictionary缓存MethodInfo提高性能。

Automapper扩展方法的更多相关文章

  1. AutoMapper 6.x 扩展方法

    简介 很多时候我们使用AutoMapper的时候,都需要进行一个配置才可以使用Mapper.Map<Source,Target>(entity);.如果不进行配置则会报错. 如果实体过多, ...

  2. ABP框架源码中的Linq扩展方法

    文件目录:aspnetboilerplate-dev\aspnetboilerplate-dev\src\Abp\Collections\Extensions\EnumerableExtensions ...

  3. AutoMapper扩展帮助类

    /// <summary> /// AutoMapper扩展帮助类 /// </summary> public static class AutoMapperExtension ...

  4. .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法

    .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法 0x00 为什么需要Map(MapWhen)扩展 如果业务逻辑比较简单的话,一条主管道就够了,确实用不到 ...

  5. .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类

    .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类 0x00 为什么要引入扩展方法 有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件.除 ...

  6. 为IEnumerable<T>添加RemoveAll<IEnumerable<T>>扩展方法--高性能篇

    最近写代码,遇到一个问题,微软基于List<T>自带的方法是public bool Remove(T item);,可是有时候我们可能会用到诸如RemoveAll<IEnumerab ...

  7. C#的扩展方法解析

    在使用面向对象的语言进行项目开发的过程中,较多的会使用到“继承”的特性,但是并非所有的场景都适合使用“继承”特性,在设计模式的一些基本原则中也有较多的提到. 继承的有关特性的使用所带来的问题:对象的继 ...

  8. 扩展方法(C#)

    扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用. 下面的示例为String添加 ...

  9. 扩展方法解决LinqToSql Contains超过2100行报错问题

    1.扩展方法 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...

随机推荐

  1. Axapta 3 COM Connector

    Axapta 3 COM Connector Copy from blog   Having fun setting up the COM+ connector for Enterprise Port ...

  2. ubuntu系统从中文环境改成英文环境

      我们在 安装ubuntu server版的时候,有人可能选择了中文环境安装,因为那样好设置时区等参数,可是安装好了后,运行某些命令的时候会有中文乱码提示,看起很是头蛋疼, 我们就需要将其改成英文环 ...

  3. python 字符串截取

    我们可以通过索引来提取想要获取的字符,可以把python的字符串也做为字符串的列表就更好理解 python的字串列表有2种取值顺序1是从左到右索引默认0开始的,最大范围是字符串长度少1s = 'ilo ...

  4. 使用sp_addextendedproperty添加描述信息

    -- For table EXECUTE sp_addextendedproperty N'MS_Description', '描述内容', N'user', N'dbo', N'table', N' ...

  5. [转]使用Xcode 4发布App 实例操作

    使用xcode 4发布app 实例操作是本文介绍的内容,不多说,我们直接进入话题. 1.iOS Provisioning Portal 和iTunes Connect 没有变,下载与安装.mobile ...

  6. java攻城师之路(Android篇)--搭建开发环境、拨打电话、发送短信、布局例子

    一.搭建开发环境 1.所需资源 JDK6以上 Eclipse3.6以上 SDK17, 2.3.3 ADT17 2.安装注意事项 不要使用中文路径 如果模拟器默认路径包含中文, 可以设置android_ ...

  7. Adroid学习系列-入门(1)

    1.  安装 安装Eclipse,安装Adroid插件.安装Adroid SDK. 2.  项目目录说明 2.1.       建立Adroid项目 与一般的Java项目一样 )src文件夹是项目的所 ...

  8. MongoDB的学习--文档的插入、删除和更新

    最近在看<MongoDB权威指南>,写博客记录一下相关内容~~ 关于安装之类的最基本的就不多说了,从基本操作增删改查开始. MongoDB官网地址:http://www.mongodb.o ...

  9. python关键字详解

    今天依旧在啃:<笨方法学python>,其中习题37是复习各种关键字.我本想百度一下记一下就ok了,但是百度出来第一个就Hongten的博客.我才意识到我也有博客,我应该学习他,把这些积累 ...

  10. js关于对象键值为数字型时输出的对象自动排序问题的解决方法

    一.对象键值为数字型时输出的对象自动排序问题如: var objs = {    "1603":{id:"1603"},    "1702" ...