简介

很多时候我们使用AutoMapper的时候,都需要进行一个配置才可以使用Mapper.Map<Source,Target>(entity);。如果不进行配置则会报错。
如果实体过多,有时候会忘记是否有配置,只有运行的时候才会发现这个BUG。

Github地址

源代码

该扩展基于AutoMapper 6.x版本,因此需要从Nuget下载相应的包。
该扩展对于Object以及List<T>进行了兼容支持,因此MapTo<TSource,TDestination>()可以直接映射实体与泛型列表。

/// <summary>
/// AutoMapper扩展
/// </summary>
public static class Extensions
{
    /// <summary>
    /// 将源对象映射到目标对象
    /// </summary>
    /// <typeparam name="TSource">源类型</typeparam>
    /// <typeparam name="TDestination">目标类型</typeparam>
    /// <param name="source">源对象</param>
    /// <param name="destination">目标对象</param>
    /// <returns></returns>
    public static TDestination MapTo<TSource, TDestination>(this TSource source, TDestination destination)
    {
        return MapTo<TDestination>(source, destination);
    }

    /// <summary>
    /// 将源对象映射到目标对象
    /// </summary>
    /// <typeparam name="TSource">源类型</typeparam>
    /// <typeparam name="TDestination">目标类型</typeparam>
    /// <param name="source">源对象</param>
    /// <returns></returns>
    public static TDestination MapTo<TSource, TDestination>(this TSource source) where TDestination : new()
    {
        return MapTo(source, new TDestination());
    }

    /// <summary>
    /// 将源对象映射到目标对象
    /// </summary>
    /// <typeparam name="TDestination">目标类型</typeparam>
    /// <param name="source">源对象</param>
    /// <param name="destination">目标对象</param>
    /// <returns></returns>
    private static TDestination MapTo<TDestination>(object source, TDestination destination)
    {
        if (source == null)
        {
            throw new ArgumentNullException(nameof(source));
        }
        if (destination == null)
        {
            throw new ArgumentNullException(nameof(destination));
        }
        var sourceType = GetObjectType(source.GetType());
        var destinationType = GetObjectType(typeof(TDestination));
        try
        {
            var map = Mapper.Configuration.FindTypeMapFor(sourceType,destinationType);
            if (map != null)
            {
                return Mapper.Map(source, destination);
            }
            var maps = Mapper.Configuration.GetAllTypeMaps();
            Mapper.Initialize(config =>
            {
                foreach (var item in maps)
                {
                    config.CreateMap(item.SourceType, item.DestinationType);
                }
                config.CreateMap(sourceType,destinationType);
            });

        }
        catch (InvalidOperationException)
        {
            Mapper.Initialize(config =>
            {
                config.CreateMap(sourceType, destinationType);
            });
        }
        return Mapper.Map(source, destination);
    }

    /// <summary>
    /// 获取对象类型
    /// </summary>
    /// <param name="source">类型</param>
    /// <returns></returns>
    private static Type GetObjectType(Type source)
    {
        if (source.IsGenericType && typeof(IEnumerable).IsAssignableFrom(source))
        {
            var type = source.GetGenericArguments()[0];
            return GetObjectType(type);
        }
        return source;
    }
}

参考

何镇汐大大

AutoMapper 6.x 扩展方法的更多相关文章

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

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

  2. C# AutoMapper的简单扩展

    AutoMapper可以很方便的将一个实体的属性值转化给另一个对象.这个功能在我们日常的编码中经常会遇到.我将AutoMapper的一些基本映射功能做成扩展方法,在编码中更方便使用. using Sy ...

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

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

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

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

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

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

  6. C#的扩展方法解析

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

  7. 扩展方法(C#)

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

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

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

  9. C#扩展方法

    扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法就相当于一个马甲,给一个现有类套上,就可以为这个类添加其他方法了. 马甲必须定义为stati ...

随机推荐

  1. SG函数学(hua)习(shui)记录

    ---恢复内容开始--- 听说有一个东西叫SG函数 觉得自己好像原来是懂一些粗浅的应用但现在感觉要再深♂入一点呢 让我们先来介绍一下SG函数吧 这是某类满足下列条件的玄学博弈问题解法 双人.回合制: ...

  2. apply/call/bind和this的使用

    fun.apply(context,[argsArray]) 立即调用fun,同时将fun函数原来的this指向传入的新context对象,实现同一个方法在不同对象上重复使用. context:传入的 ...

  3. 为什么重写equals时必须重写hashCode方法?(转发+整理)

    为什么重写equals时必须重写hashCode方法? 原文地址:http://www.cnblogs.com/shenliang123/archive/2012/04/16/2452206.html ...

  4. Android onclick监听事件打开新界面

    一.新建工程 二.新建XML代码 新建一个Button <Button android:layout_width="wrap_content" android:layout_ ...

  5. RPi WiringPi安装使用

    sudo apt-get install git-core git clone git://git.drogon.net/wiringPi   cd wiringPi ./build   使用Exam ...

  6. spring-线程池(3)

    一.初始化 1,直接调用 import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import org.springframe ...

  7. 测试class

    各种断言方法: assertEqual(a,b) a == b assertNotEqual(a,b) a != b assertTrue(x) x == True assertFalse(x) x ...

  8. [原创]MongoDB综合实例二

    MongoDB-Sharding部署方案 一.    部署环境 五台主机: Amongoshard01:  10.212.74.43 Amongoshard02:  10.212.84.4 Among ...

  9. 在Azure China用自定义镜像创建Azure VM Scale Set

    在Azure China用自定义镜像创建Azure VM Scale Set 在此感谢世纪互联的工程师Johnny Lee和Lan,你们给了我很大的帮助.因为Azure China的官网没有给出完整的 ...

  10. 全景智慧城市常诚——没接触过VR全景的你就是目前VR最大的新闻

    据调查,自2015年开始,VR(虚拟现实)技术在传媒行业中的应用呈现井喷式增长,各大国际主流媒体纷纷在新闻报道中使用VR技术.国内运用VR报道新闻最早在2015年12月,财新网利用VR技术对深圳山体垮 ...