感谢您阅读我的博客,如果您现在工作、学习累了或者疲惫了,不妨聆听一下音乐,它能够减轻你的疲劳,还能够带给您一种舒适愉悦的心情。如果您认为这篇文章还不错或者有所收获,您可以在页面 右侧和底部 扫描二维码 打赏我,您的鼓励是我继续写作、分享的最大动力!

C#使用AutoMapper

using System;
using AutoMapper;

namespace AutoMapperDemo02
{
    /// <summary>
    ///     https://blog.csdn.net/u014180504/article/details/88722555
    ///     AutoMapper用法
    ///     Nuget: AutoMapper 8.0.0, AutoMapper.Data 2.0.0
    ///     版本是8.0.0 由于8.0要求 .net framework 4.6+ ,而现有项目都是4.5 所以这里直接安装的7.0.1 , AutoMapper.Data选择的是2.0.0
    ///     这个后面是用来实现IDataReader转List的
    ///     问题:System.InvalidOperationException:“Mapper already initialized. You must call Initialize once per application
    ///     domain/process.”
    ///     原因:Mapper.Initialize 只能执行一次,你的代码中多次执行了 Mapper.Initialize
    /// </summary>
    internal class Program
    {
        private static void Main()
        {
            Console.Title = "AutoMapper用法";

            // 注册映射关系
            MapperInitialize();

            Console.WriteLine("基础模型转换");
            Usage01(); // 基础模型转换
            Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            Console.WriteLine("反向映射转换");
            Usage02(); // 反向映射转换
            Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            Console.WriteLine("自定义映射规则");
            Usage03(); // 自定义映射规则
            Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");

            Console.ReadKey();
        }

        /// <summary>
        ///     注册映射关系(只能运行一次)
        /// </summary>
        private static void MapperInitialize()
        {
            Mapper.Initialize(cfg =>
            {
                // 注册映射关系【基础模型转换】
                cfg.CreateMap<Student, StudentDto>();

                // 注册映射关系【反向映射转换】
                cfg.CreateMap<Order, OrderDto>().ReverseMap();

                // 注册映射关系【自定义映射规则】
                cfg.CreateMap<string, int>().ConvertUsing(s => Convert.ToInt32(s));
                cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
                cfg.CreateMap<Source, Destination>();
            });
        }

        /// <summary>
        ///     自定义映射规则
        /// </summary>
        private static void Usage03()
        {
            Mapper.AssertConfigurationIsValid();

            var source = new Source
            {
                Value1 = "5",
                Value2 = "01/01/2000",
                Value3 = "1.222"
            };

            var result = Mapper.Map<Source, Destination>(source);
            Console.WriteLine("Value1:" + result.Value1);
            Console.WriteLine("Value2:" + result.Value2);
            Console.WriteLine("Value3:" + result.Value3);
        }


        /// <summary>
        ///     反向映射转换
        /// </summary>
        private static void Usage02()
        {
            var customer = new Customer {Name = "Bob"};

            var order = new Order {Customer = customer, Total = 15.8m};

            var orderDto = Mapper.Map<Order, OrderDto>(order);
            orderDto.CustomerName = "Joe";

            var o = Mapper.Map(orderDto, order);
            Console.WriteLine("Customer.Name:" + o.Customer.Name);
            Console.WriteLine("Total:" + o.Total);
        }

        /// <summary>
        ///     基础模型转换
        /// </summary>
        private static void Usage01()
        {
            var student = new Student {Id = 1, Name = "LDH", Address = "Shanghai"};
            var studentDto = Mapper.Map<StudentDto>(student);

            Console.WriteLine("StudentDto对象属性值如下:");

            Console.WriteLine("Id:" + studentDto.Id);
            Console.WriteLine("Name:" + studentDto.Name);
            Console.WriteLine("Address:" + studentDto.Address);
        }
    }

    #region 反向映射转换 实体类

    public class Order
    {
        public decimal Total { get; set; }
        public Customer Customer { get; set; }
    }

    public class Customer
    {
        public string Name { get; set; }
    }

    public class OrderDto
    {
        public decimal Total { get; set; }
        public string CustomerName { get; set; }
    }

    #endregion

    #region 基础模型转换 实体类

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

    public class StudentDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
    }

    #endregion

    #region 自定义映射规则 实体

    public class Source
    {
        public string Value1 { get; set; }
        public string Value2 { get; set; }
        public string Value3 { get; set; }
    }

    public class Destination
    {
        public int Value1 { get; set; }
        public DateTime Value2 { get; set; }
        public double Value3 { get; set; }
    }

    public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
    {
        public DateTime Convert(string source, DateTime destination, ResolutionContext context)
        {
            return System.Convert.ToDateTime(source);
        }
    }

    #endregion
}

posted @ 2021-09-03 14:24  Love In Winter  阅读(551)  评论(0编辑  收藏  举报
作者: LifeDecidesHappiness
出处: http://www.cnblogs.com/LifeDecidesHappiness/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,否则保留追究法律责任的权利,且在文章页面明显位置给出原文连接,如有问题,可以通过以下邮箱地址 2468881301@qq.com  联系我,非常感谢。
踏实做一个为人民服务的搬运工!
如果您认为这篇文章还不错或者有所收获,您可以通过右边的“打赏”功能,您的支持和鼓励是我继续写作、分享的最大动力!

点击关注不迷路,让我带你上高速!