c# AutoMapper 扩展

摘要:
下面直接上代码扩展方法publicstaticclassExt{#region对象或集合,字段不一致自定义转换规则Mapping//////集合列表类型映射,默认字段名字一一对应//////转化之后的model,可以理解为viewmodel///˂typeparamname="TSour

下面直接上代码


扩展方法
    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
    }

测试:

c# AutoMapper 扩展第1张c# AutoMapper 扩展第2张
usingAutoMapper;
usingSystem;
usingSystem.Collections.Generic;

namespaceConsoleApp1
{
    classProgram
    {
        static void Main(string[] args)
        {
            Mapp();
            Console.WriteLine("Hello World!");
        }
        static voidMapp()
        {
            #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) });
            }
            #endregionDestination 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 classSource
    {
        public DateTime CurrentDateTime { get; set; }
    }
    public classDestination
    {
        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

效果图:

c# AutoMapper 扩展第3张

c# AutoMapper 扩展第4张

免责声明:文章转载自《c# AutoMapper 扩展》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇前端性能优化常用方法mysql hang and srv_error_monitor_thread using 100% cpu(已解决)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

AutoMapper(三)

返回总目录 自定义类型转换 有时,需要完全控制一个类型到另一个类型的转换。一个类型一点都不像另一个类型,而且转换函数已经存在了,在这种情况下,你想要从一个“宽松”的类型转换成一个更强壮的类型,例如一个string的源类型到一个int32的目标类型。 这里有两个类Source和Destination,要把前者映射到后者,代码如下: public class...

安装centos7模板机[lvm版]

1. 安装centos 7模板机 准备好centos7的镜像 下载地址:http://mirrors.aliyun.com/centos/7/isos/x86_64/ 安装centos 自定义硬件: 对硬件进行一些修改 支持虚拟化 开启虚拟化支持: 配置完成后 点击确定 然后开机 将这段文字修改为: vmlinuz initrd=i...

Mybatis之collection与association标签

collection与association标签的功能就是为了解决查询条件映射到一个类或一个集合上,适用于对于多对一,一对多的映射结果,现在我们就探究其具体使用吧。 环境搭建: 数据库搭建 CREATE TABLEteacher ( id INT(10) NOT NULL, name VARCHAR(30) DEFAULT NULL, PRI...

AutoMapper 忽略某个字段

以前要在定义中忽略 Mapper.CreateMap<Source, Destination>() .ForMember(dest => dest.SomeValuefff, opt => opt.Ignore());    一直在找更方便的方法,今天在一篇博客中发现,如果字段是virtual类型的,那么也会被忽略掉。...

[MyBatis]五分钟向MySql数据库插入一千万条数据 批量插入 用时5分左右

本例代码下载:https://files.cnblogs.com/files/xiandedanteng/InsertMillionComparison20191012.rar 我的数据库环境是mysql Ver 14.14 Distrib 5.6.45, for Linux (x86_64) using EditLine wrapper 这个数据库是安装...

.Net Core + DDD基础分层 + 项目基本框架 + 个人总结

为什么要写这篇文章 1,在大半年前,公司开发任务比较轻松,自己不知道干什么,但是又想要学习技术,比较迷茫,后面我接触到了博客园,看了一个帖子,深有感触,我当时不知道学习什么,于是我信息给他,他居然回复我了,并且还给我建议学习的方向,以及学习的方法,我十分的感谢他。 2,在一次面试中,有人问我,你工作1年多了有没有做过自我总结,你觉得你的优势是什么,我当时吞...