Automapper扩展方法
问题描述
系统中实现了一个自定义的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扩展方法的更多相关文章
- AutoMapper 6.x 扩展方法
简介 很多时候我们使用AutoMapper的时候,都需要进行一个配置才可以使用Mapper.Map<Source,Target>(entity);.如果不进行配置则会报错. 如果实体过多, ...
- ABP框架源码中的Linq扩展方法
文件目录:aspnetboilerplate-dev\aspnetboilerplate-dev\src\Abp\Collections\Extensions\EnumerableExtensions ...
- AutoMapper扩展帮助类
/// <summary> /// AutoMapper扩展帮助类 /// </summary> public static class AutoMapperExtension ...
- .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法
.NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法 0x00 为什么需要Map(MapWhen)扩展 如果业务逻辑比较简单的话,一条主管道就够了,确实用不到 ...
- .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类
.NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类 0x00 为什么要引入扩展方法 有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件.除 ...
- 为IEnumerable<T>添加RemoveAll<IEnumerable<T>>扩展方法--高性能篇
最近写代码,遇到一个问题,微软基于List<T>自带的方法是public bool Remove(T item);,可是有时候我们可能会用到诸如RemoveAll<IEnumerab ...
- C#的扩展方法解析
在使用面向对象的语言进行项目开发的过程中,较多的会使用到“继承”的特性,但是并非所有的场景都适合使用“继承”特性,在设计模式的一些基本原则中也有较多的提到. 继承的有关特性的使用所带来的问题:对象的继 ...
- 扩展方法(C#)
扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用. 下面的示例为String添加 ...
- 扩展方法解决LinqToSql Contains超过2100行报错问题
1.扩展方法 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...
随机推荐
- Selenium Grid 学习笔记
Selenium Grid 学习笔记http://www.docin.com/p-765680298.html
- Android不规则点击区域详解
Android不规则点击区域详解 摘要 今天要和大家分享的是Android不规则点击区域,准确说是在视觉上不规则的图像点击响应区域分发. 其实这个问题比较简单,对于很多人来说根本不值得做为一篇博文写出 ...
- nginx后的tomcat获取真实用户ip
目前大部分获取ip的方式:beat.getRequest().getRemoteAddr()但是,如果通过nginx反向代理的话,就获取不到真实ip,是获取的nginx的ip 需要:添加 pro ...
- coreseek 提示 client version is higher than daemon version 解决办法
安装好coreseek,开启了服务之后,通过 sphinx php扩展去请求数据,提示:client version is higher than daemon version (client is ...
- oracle 12541,12560,00511无监听程序, 协议适配器错误问题分析及解决方案
oracle 12541,12560,00511无监听程序, 协议适配器错误问题分析及解决方案 问题描述: 1. lsnrctl start.stop.非常慢,出现卡顿现象: 2. 执行lsnrc ...
- Entity Framework访问MySQL数据库的存储过程并获取返回值
一.创建MySql存储过程 1, CREATE PROCEDURE `InsertAlarmInfo`(in businessindex int, in providerindex int, in ...
- Android 布局之TableLayout
Android 布局之TableLayout 1 TableLayout简介 TableLayout是表格布局.TableLayout 可设置的属性包括全局属性及单元格属性. 1.1 全局属性 有以下 ...
- How to implement an algorithm from a scientific paper
Author: Emmanuel Goossaert 翻译 This article is a short guide to implementing an algorithm from a scie ...
- 1、图解Oracle Logminer配置使用
LogMiner配置使用手册 1 Logminer简介 1.1 LogMiner介绍 Oracle LogMiner 是Oracle公司从产品8i以后提供的一个实际非常有用的分析工具,使用该工具可以轻 ...
- Tools - 常用搜索引擎命令
site 用来查询网站收录量. 比如site:http://www.cnblogs.com/ inurl 查URL中包含的元素,比如inurl:bbs ,搜索出URL包含bbs的页面. 常用的inur ...