zoukankan      html  css  js  c++  java
  • AutoMapper

    AutoMapper 创建嵌套对象映射(原创)

    之前在做DTO转换时,用到AutoMapper。但DTO的层次太深了,无奈官方没针对嵌套类型提供好的解决方案,于是自己实现了一下:

    思路:采用递归和反射很好的避免手工创建嵌套对象的映射。

    第一个版本,已经提交到:https://github.com/AutoMapper/AutoMapper/wiki/Nested-mappings

     

    /// <summary>
    /// 递归创建类型间的映射关系 (Recursively create mappings between types)
    ///created by cqwang
    /// </summary>
    /// <param name="sourceType"></param>
    /// <param name="destinationType"></param>
    public static void CreateNestedMappers(Type sourceType, Type destinationType)
    {
    PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    PropertyInfo[] destinationProperties = destinationType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    foreach (var destinationProperty in destinationProperties)
    {
    Type destinationPropertyType = destinationProperty.PropertyType;
    if (Filter(destinationPropertyType))
    continue;

    PropertyInfo sourceProperty = sourceProperties.FirstOrDefault(prop => NameMatches(prop.Name, destinationProperty.Name));
    if (sourceProperty == null)
    continue;

    Type sourcePropertyType=sourceProperty.PropertyType;
    if (destinationPropertyType.IsGenericType)
    {
    Type destinationGenericType = destinationPropertyType.GetGenericArguments()[0];
    if (Filter(destinationGenericType))
    continue;

    Type sourceGenericType = sourcePropertyType.GetGenericArguments()[0];
    CreateMappers(sourceGenericType, destinationGenericType);
    }
    else
    {
    CreateMappers(sourcePropertyType, destinationPropertyType);
    }
    }

    Mapper.CreateMap(sourceType, destinationType);
    }

    /// <summary>
    /// 过滤 (Filter)
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    static bool Filter(Type type)
    {
    return type.IsPrimitive || NoPrimitiveTypes.Contains(type.Name);
    }

    static readonly HashSet<string> NoPrimitiveTypes = new HashSet<string>() { "String", "DateTime", "Decimal" };

    private static bool NameMatches(string memberName, string nameToMatch)
    {
    return String.Compare(memberName, nameToMatch, StringComparison.OrdinalIgnoreCase) == 0;
    }

    后来自测中发现,要过滤的一些结构体可能很多,比较麻烦,所以自己又完善了下,有了第二个版本

    第二个版本在公司内的一些服务中已经使用并上线,挺好。因为并未涉及到公司内的任何业务信息,只是简单的思路和实现,所以这里贴出来给大家分享一下。

    所有代码为原创,转载请注明出处。

    其实,本没有路,走过去,便是路。

     
    分类: 程序人生
  • 相关阅读:
    《游戏改变世界》笔记
    2017第6周日
    换个角度看执行力
    怎样拥有执行力和高效能
    提高个人执行力的五个关键
    Apache服务器部署多个进程
    IE的Cookie目录和临时缓存目录的关系
    IE/Firefox/Chrome等浏览器保存Cookie的位置
    在浏览器中简单输入一个网址,解密其后发生的一切(http请求的详细过程)
    如何设置win7系统的文件夹为系统文件,从而隐藏文件夹
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/4182246.html
Copyright © 2011-2022 走看看