• c# AutoMapper 扩展


    下面直接上代码


    扩展方法

        public static class Ext
        {
            #region 对象或集合,字段不一致 自定义转换规则 Mapping
            /// <summary>
            /// 集合列表类型映射,默认字段名字一一对应
            /// </summary>
            /// <typeparam name="TResult">转化之后的model,可以理解为viewmodel</typeparam>
            /// <typeparam name="TSource">要被转化的实体,Entity</typeparam>
            /// <param name="source">可以使用这个扩展方法的类型,任何引用类型</param>
            /// <returns>转化之后的实体列表</returns>
            public static TResult ToMap<TSource, TResult>(this TSource source, MapperConfiguration config) where TResult : class where TSource : class
            {
                if (source == null) return default(TResult);
                return config.CreateMapper().Map<TResult>(source);
            }
            #endregion
    
            #region 字段一致之间转换
    
            #region 字段一致对象实体之间转换
            /// <summary>
            /// 字段一致对象实体之间转换
            /// </summary>
            /// <typeparam name="TResult"></typeparam>
            /// <param name="self"></param>
            /// <returns></returns>
            public static TResult ToMap<TSource, TResult>(this TSource source)
            {
                if (source == null)
                    return default(TResult);
                Mapper.Reset();
                Mapper.Initialize(x => x.CreateMap<TSource, TResult>());
                return Mapper.Map<TResult>(source);
            }
            #endregion
    
            #region 字段一致集合之间转换
            /// <summary>
            /// 字段一致集合之间转换
            /// </summary>
            /// <typeparam name="TSource"></typeparam>
            /// <typeparam name="TResult"></typeparam>
            /// <param name="source"></param>
            /// <returns></returns>
            public static IEnumerable<TResult> ToMap<TSource, TResult>(this IEnumerable source)
            {
                if (source == null) return default(IEnumerable<TResult>);
                Mapper.Reset();
                Mapper.Initialize(x => x.CreateMap<TSource, TResult>());
                return Mapper.Map(source, source.GetType(), typeof(IEnumerable<TResult>)) as IEnumerable<TResult>;
            }
            #endregion 
    
            #endregion
        }
    

      


    测试:

    using AutoMapper;
    using System;
    using System.Collections.Generic;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Mapp();
                Console.WriteLine("Hello World!");
            }
            static void Mapp()
            {
                #region 实例一 源实体与转换后实体字段不一致 指定字段一一对应,并转化指定的格式
                var config = new MapperConfiguration(cfg => cfg.CreateMap<Source, Destination>()
                #region MapFrom 指定字段一一对应,并转化指定的格式
                 .ForMember(d => d.Year, o => o.MapFrom(src => $"年:{src.CurrentDateTime.Year}"))
                 .ForMember(d => d.Month, o => o.MapFrom(src => $"月:{src.CurrentDateTime.Month}"))
                 .ForMember(d => d.Day, o => o.MapFrom(src => $"日:{src.CurrentDateTime.Day}"))
                 .ForMember(d => d.Hour, o => o.MapFrom(src => $"时:{ src.CurrentDateTime.Hour}"))
                 .ForMember(d => d.Minute, o => o.MapFrom(src => $"分:{src.CurrentDateTime.Minute}"))
                 .ForMember(d => d.Second, o => o.MapFrom(src => $"秒:{src.CurrentDateTime.Second}"))
                 .ForMember(d => d.DateTime, o => o.MapFrom(src => $"{src.CurrentDateTime.ToLocalTime()}"))
                #endregion
                );
                Source source = new Source { CurrentDateTime = DateTime.Now };
                List<Source> sourceList = new List<Source>();
                for (int i = 0; i < 1000; i++)
                {
                    sourceList.Add(new Source { CurrentDateTime = DateTime.Now.AddDays(i) });
                }
                #endregion
                Destination result = source.ToMap<Source, Destination>(config);
                List<Destination> resultList = sourceList.ToMap<List<Source>, List<Destination>>(config);
                Destination result2 = source.ToMap<Source, Destination>();
                var resultList2 = sourceList.ToMap<Source, Destination>();
            }
        }
        public class Source
        {
            public DateTime CurrentDateTime { get; set; }
        }
        public class Destination
        {
            public string Year { get; set; }
            public string Month { get; set; }
            public string Day { get; set; }
            public string Hour { get; set; }
            public string Minute { get; set; }
            public string Second { get; set; }
            public string DateTime { get; set; }
            public DateTime currentdatetime { get; set; }
        }
    }
    View Code

     效果图:

     

  • 相关阅读:
    mysq foreign外键记录
    查询时隐藏部分身份证号
    SpringBoot接收前端参数
    RabbbitMQ安装
    @configurationProperties注解时 idea弹出 Spring Boot Annotion processor not found in classpath
    rpm,yum和apt使用详解
    python人脸识别
    Fuchsia文章汇总
    Androi O Automotive 介绍
    Linux 版本控制工具之rabbitvcs
  • 原文地址:https://www.cnblogs.com/aaaaq/p/9193719.html
Copyright © 2020-2023  润新知