问题描述

系统中实现了一个自定义的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. Linux(Centos)下jdbc连接oracle速度超慢的问题

    最近在centos下写个java swing程序,发现在linux用jdbc连接oracle及其缓慢,还经常失败.但是同样的程序在windows下运行就连接的非常快.网上搜索了很长时间都和我这情况没关 ...

  2. 基于soapUI构建WebService测试框架

    基于soapUI构建WebService测试框架 http://www.docin.com/p-775523285.html

  3. npm 发布包

    每个包都必须包含package.json配置文件 生成package.page文件 1.到项目目录下执行npm init根据提示输入即可 最后记得要yes 完成项目后就是要发布到npm了 首先需要有n ...

  4. springMVC对于controller处理方法返回值的可选类型

    http://www.360doc.com/content/14/0309/19/834950_359081989.shtml

  5. 使用Merge Into 语句实现 Insert/Update

    网址: http://www.eygle.com/digest/2009/01/merge_into_insertupdate.html 动机: 想在Oracle中用一条SQL语句直接进行Insert ...

  6. Making Your ActionBar Not Boring

    这篇文章转自国外一个技术大牛的博客,首先感谢这位大牛的无私奉献. Android应用中有一名位 Google书报摊的应用,他实现了一种新的ActionBar风格.当用户初始进入该界面的时候,为一个透明 ...

  7. Maven更新子模块的版本号

    mark! 已写成了另一篇,不要打我.

  8. VB6.0手册

    1.Form窗体事件 Private Sub Form_Activate() '焦点在此窗口时触发  MsgBox "窗体的Activate事件"  End Sub    Priv ...

  9. 论文第5章:Android绘图平台的实现

    面向移动设备的矢量绘图平台设计与实现 Design and Implementation of Mobile Device-oriented Vector Drawing Platform 引用本论文 ...

  10. 使用uploadify上传控件无法进入后台问题分析

    分别在.net mvc 和java struts2中使用到 uploadify上传 文件,遇到同样的问题,选中文件上传后,文件无法上传,打上断点后发现没有进入后台. 逐步断点发现 项目共同点是加入了 ...