AutoMapper使用总结

/// 映射的时候一定要保证目标对象的属性是可写的,要不该属性没有效果。
/// 1:扁平化映射
/// 规则:将一个复杂的多层次对象转化为一个单层对象
/// 1:如果有相同属性,则对相同属性进行映射
/// 2:如果没有同名的属性,
/// 则检查同名的方法,
/// 再再检查是否有Get开头的同名方法
/// 然后将 目标对象的属性 按照Pascal规则对属性进行分割,去映射属性
/// 并且每个单词之间还可以组合,就是属性是多个单词页能识别。
/// 属性的类型不会影响优先级关系。
/// 2:映射功能测试
/// 在属性的名字或者是属性的类型不一致的情况下,可以使用映射功能,
/// MapFrom为目标对象设置值
/// 3:映射验证
/// 检查是否所有的目标属性都有对应的映射以及类型是否一致。
/// 4:集合的映射
/// 只需要对元素进行配置就可以了,
/// IEnumerable,IEnumerable<T>,ICollection,ICollection<T>,IList,IList<T>,List<T>,Arrays
/// 都默认支持
/// 5:嵌套映射
/// 可以将一个复杂对象映射为另外的一个复杂对象
/// 6:自定义类型转换器
/// 在全局范围内,将一种类型转换为另外的一种类型
/// 比如讲string 转换为时间,将string 转换为类对象,或者将类对象转换为string等
/// 7:自定义属性值映射器
/// 主要是解决值需要通过一个函数计算来获得的情况,
/// 鸡肋功能,可以用MapFrom替代
/// 8:空值的处理
/// 当源对象为空时,目标对象的处理办法
/// 9:继承关系的映射处理
/// 继承的优先级别是:
/// a:类本身的直接映射MapFrom
/// b:继承的直接映射MapFrom
/// c:本身的Ignore映射
/// d:默认规则映射
/// e:继承的Ignore映射
/// 需要注意的是 NullSubstitute没有被继承下来,需要在子类里接着写
/// 10:条件映射处理Condition
/// 当满足条件时才能进行映射处理
/// 11:创建动态映射
/// 当源数据类型不是那么严格时,可以使用动态映射DynamicMap

定义数据结构:

    #region 数据库结构信息
    public class CustomerInfo : ModelBase
    {
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name = string.Empty;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private List<OrderInfo> orders = new List<OrderInfo>();

        public List<OrderInfo> Orders
        {
            get { return orders; }
            set { orders = value; }
        }

        public int OrderCount
        {
            get
            {
                if (orders == null)
                {
                    return 0;
                }
                return orders.Count;
            }
        }

        public OrderInfo MainOrder
        {
            get
            {
                if (orders.Count > 0)
                {
                    return orders[0];
                }
                return null;
            }
        }

        public int GetName()
        {
            return 100;
        }
    }
    public class OrderInfo : ModelBase
    {
        private string name = "";

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private DateTime createDate = DateTime.Now;

        public DateTime CreateDate
        {
            get { return createDate; }
            set { createDate = value; }
        }
        private PaymentInfo payment = null;

        public PaymentInfo Payment
        {
            get { return payment; }
            set { payment = value; }
        }
        private Guid customerId = Guid.Empty;

        public Guid CustomerId
        {
            get { return customerId; }
            set { customerId = value; }
        }
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }
        private CustomerInfo customer = null;

        public CustomerInfo Customer
        {
            get { return customer; }
            set { customer = value; }
        }
        private List<OrderItemInfo> orderItems = new List<OrderItemInfo>();

        public List<OrderItemInfo> OrderItems
        {
            get { return orderItems; }
            set { orderItems = value; }
        }
        public int GetItemsCount()
        {
            if (orderItems == null)
            {
                return 0;
            }
            return orderItems.Count;
        }

        public string SameProperty1
        {
            get
            {
                return "相同属性";
            }
        }
        public string GetSameProperty1()
        {
            return "方法——相同属性";
        }

        public int SameProperty2
        {
            get
            {
                return 222;
            }
        }
        public string GetSameProperty2()
        {
            return "方法——222相同属性";
        }

        public string SameProperty3
        {
            get
            {
                return "222";
            }
        }
        public int GetSameProperty3()
        {
            return 222;
        }
    }
    public class TelephoneOrderInfo : OrderInfo
    {
        private string telephone = "";
        public string Telephone
        {
            get { return telephone; }
            set { telephone = value; }
        }
    }
    public class WeixinOrderInfo : OrderInfo
    {
        private string openId = "";
        public string OpenId
        {
            get { return openId; }
            set { openId = value; }
        }
    }
    public class OrderItemInfo : ModelBase
    {
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }
        private int count = 0;

        public int Count
        {
            get { return count; }
            set { count = value; }
        }
        private OrderInfo order = null;

        public OrderInfo Order
        {
            get { return order; }
            set { order = value; }
        }
        private Guid goodsId = Guid.Empty;

        public Guid GoodsId
        {
            get { return goodsId; }
            set { goodsId = value; }
        }
        private GoodsInfo goods = null;

        public GoodsInfo Goods
        {
            get { return goods; }
            set { goods = value; }
        }
    }
    public class GoodsInfo : ModelBase
    {
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }

        private string name = string.Empty;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private decimal price = 0;

        public decimal Price
        {
            get { return price; }
            set { price = value; }
        }
        private int goodsType = 0;

        public int GoodsType
        {
            get { return goodsType; }
            set { goodsType = value; }
        }
    }
    public class PaymentInfo : ModelBase
    {
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }
        private DateTime payDate = DateTime.MinValue;

        public DateTime PayDate
        {
            get { return payDate; }
            set { payDate = value; }
        }
    }

    #endregion 数据库结构信息

    #region 前端展现信息
    public class CustomerInfoVModel : ModelBase
    {
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name = string.Empty;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        private int orderCount = 0;

        public int OrderCount
        {
            get { return orderCount; }
            set { orderCount = value; }
        }
    }

    public class OrderInfoVModel : ModelBase
    {
        private string payment = string.Empty;

        public string Payment
        {
            get { return payment; }
            set { payment = value; }
        }

        private CustomerInfoVModel customer2;

        public CustomerInfoVModel Customer2
        {
            get { return customer2; }
            set { customer2 = value; }
        }

        private string customerMainOrderSameProperty1 = "";

        public string CustomerMainOrderSameProperty1
        {
            get { return customerMainOrderSameProperty1; }
            set { customerMainOrderSameProperty1 = value; }
        }

        private int customerMainOrderSameProperty2 = 0;

        public int CustomerMainOrderSameProperty2
        {
            get { return customerMainOrderSameProperty2; }
            set { customerMainOrderSameProperty2 = value; }
        }
        private int customerMainOrderSameProperty3 = 0;

        public int CustomerMainOrderSameProperty3
        {
            get { return customerMainOrderSameProperty3; }
            set { customerMainOrderSameProperty3 = value; }
        }

        private string customerMainOrderName = "";

        public string CustomerMainOrderName
        {
            get { return customerMainOrderName; }
            set { customerMainOrderName = value; }
        }
        private DateTime customerMainOrderCreateDate = DateTime.Now;

        public DateTime CustomerMainOrderCreateDate
        {
            get { return customerMainOrderCreateDate; }
            set { customerMainOrderCreateDate = value; }
        }

        private decimal totalAmount = 0;

        public decimal TotalAmount
        {
            get { return totalAmount; }
            set { totalAmount = value; }
        }
        private DateTime createDate = DateTime.Now;

        public DateTime CreateDate
        {
            get { return createDate; }
            set { createDate = value; }
        }

        private string customerName = "";

        public string CustomerName
        {
            get { return customerName; }
            set { customerName = value; }
        }
        private int customerOrderCount = 0;

        public int CustomerOrderCount
        {
            get { return customerOrderCount; }
            set { customerOrderCount = value; }
        }

        private int itemsCount = 0;

        public int ItemsCount
        {
            get { return itemsCount; }
            set { itemsCount = value; }
        }

        private string yearMonth = "";

        public string YearMonth
        {
            get { return yearMonth; }
            set { yearMonth = value; }
        }

        List<string> orderItemDescs = new List<string>();

        public List<string> OrderItemDescs
        {
            get { return orderItemDescs; }
            set { orderItemDescs = value; }
        }

    }

    public class OrderItemInfoVModel : ModelBase
    {
        private Guid id = Guid.Empty;

        public Guid Id
        {
            get { return id; }
            set { id = value; }
        }
        private int count = 0;

        public int Count
        {
            get { return count; }
            set { count = value; }
        }
        private Guid orderId = Guid.Empty;

        public Guid OrderId
        {
            get { return orderId; }
            set { orderId = value; }
        }
        private string goodsName = "";

        public string GoodsName
        {
            get { return goodsName; }
            set { goodsName = value; }
        }
        private decimal goodsPrice = 0;

        public decimal GoodsPrice
        {
            get { return goodsPrice; }
            set { goodsPrice = value; }
        }
        private decimal totalAmount = 0;

        public decimal TotalAmount
        {
            get { return totalAmount; }
            set { totalAmount = value; }
        }
    }

    public class TelephoneOrderInfoVModel : OrderInfoVModel
    {
        private string telephone = "";
        public string Telephone
        {
            get { return telephone; }
            set { telephone = value; }
        }
    }

    public class WeixinOrderInfoVModel : OrderInfoVModel
    {
        private string openId = "";
        public string OpenId
        {
            get { return openId; }
            set { openId = value; }
        }
    }

    #endregion 前端展现信息

    public class ModelBase
    {
        public override string ToString()
        {
            List<PropertyInfo> properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
            StringBuilder sb = new StringBuilder();
            properties.ForEach(o =>
            {
                if ((o.PropertyType.IsValueType || o.PropertyType == typeof(string)) && o.CanRead)
                {
                    sb.AppendFormat("{0}:{1}{2}", o.Name, o.GetValue(this, null), Environment.NewLine);
                }
            });
            return sb.ToString();
        }
    }

  初始化数据:

        public CustomerInfo GetInitialData()
        {
            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.Id = Guid.NewGuid();
            customerInfo.Name = "zhu";
            customerInfo.Orders = new List<OrderInfo>();
            Random random = new Random();

            List<GoodsInfo> goods = new List<GoodsInfo>();
            int goodsCount = random.Next(30) + 10;
            for (int i = 0; i < goodsCount; i++)
            {
                goods.Add(new GoodsInfo()
                {
                    Id = Guid.NewGuid(),
                    Name = "商品" + i.ToString(),
                    GoodsType = random.Next(5),
                    Price = random.Next(200) + 2
                });
            }

            int ordersCount = random.Next(10) + 5;
            for (int i = 0; i < ordersCount; i++)
            {
                if ((i % 2) == 0)
                {
                    customerInfo.Orders.Add(new TelephoneOrderInfo()
                    {
                        Telephone = "电话号码:" + i.ToString()
                    });
                }
                else
                {
                    customerInfo.Orders.Add(new WeixinOrderInfo()
                    {
                        OpenId = "微信号:" + i.ToString()
                    });
                }

            }
            customerInfo.Orders.ForEach(o =>
            {
                o.Id = Guid.NewGuid();
                o.CreateDate = DateTime.Now.AddDays(random.Next(365));
                o.Customer = customerInfo;
                o.CustomerId = customerInfo.Id;
                o.Name = string.Format("{0}订单{1}", customerInfo.Name, o.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                o.OrderItems = new List<OrderItemInfo>();
                int orderItemsCount = random.Next(5) + 1;
                for (int i = 0; i < orderItemsCount; i++)
                {
                    o.OrderItems.Add(new OrderItemInfo()
                    {
                        Count = 1 + random.Next(6),
                        Id = Guid.NewGuid(),
                        Goods = goods[random.Next(goods.Count)]
                    });
                    o.OrderItems.ForEach(oi =>
                    {
                        oi.GoodsId = oi.Goods.Id;
                        oi.Order = o;
                    });
                }
            });
            return customerInfo;
        }

  功能测试:

       CustomerInfo customerInfo = GetInitialData();
            Mapper.CreateMap<string, int>().ConvertUsing(Convert.ToInt32);
            Mapper.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
            Mapper.CreateMap<OrderItemInfo, string>().ConvertUsing(o => o.ToString().Replace(Environment.NewLine, "---"));

            Mapper.CreateMap<CustomerInfo, CustomerInfoVModel>();
            Mapper.CreateMap<OrderInfo, OrderInfoVModel>()
                .Include<TelephoneOrderInfo, TelephoneOrderInfoVModel>()
                .Include<WeixinOrderInfo, WeixinOrderInfoVModel>()
                .ForMember(o => o.Customer2, d => d.MapFrom(df => df.Customer))
                .ForMember(o => o.OrderItemDescs, d => d.MapFrom(df => df.OrderItems))
                .ForMember(o => o.Payment, d => d.NullSubstitute("还没有做订单管理"))
                .ForMember(o => o.YearMonth, d => d.MapFrom(df => df.CreateDate.ToString("yyyyMM")));
            Mapper.CreateMap<TelephoneOrderInfo, TelephoneOrderInfoVModel>()
                .ForMember(o => o.Payment, d => d.NullSubstitute("还没有做订单管理"));
            Mapper.CreateMap<WeixinOrderInfo, WeixinOrderInfoVModel>()
                .ForMember(o => o.Payment, d => d.NullSubstitute("还没有做订单管理"));

            /// Mapper.AssertConfigurationIsValid();
            txtMsg.Text = "";
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("扁平映射");
            OrderInfoVModel vModel = Mapper.Map<OrderInfo, OrderInfoVModel>(customerInfo.Orders[3]);
            sb.AppendLine(vModel.ToString());
            sb.AppendLine("嵌套映射");
            sb.AppendLine(vModel.Customer2.ToString());
            sb.AppendLine("自定义转换器映射");
            sb.AppendLine(string.Join(Environment.NewLine, vModel.OrderItemDescs));
            sb.AppendLine("空对象处理");
            sb.AppendLine(vModel.Payment);

            var orders = Mapper.Map<List<OrderInfo>, List<OrderInfoVModel>>(customerInfo.Orders);
            orders.ForEach(o => sb.AppendLine(o.ToString()));

            DataTable dt = new DataTable();
            dt.Columns.Add("Id", typeof(Guid));
            dt.Columns.Add("Name");
            for (int i = 0; i < 10; i++)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = Guid.NewGuid();
                dr["Name"] = "姓名" + i.ToString();
                dt.Rows.Add(dr);
            }

            List<CustomerInfoVModel> customers = Mapper.DynamicMap<List<CustomerInfoVModel>>(dt.CreateDataReader());
            sb.AppendLine("DynamicMap动态映射处理");
            customers.ForEach(o => sb.AppendLine(o.ToString()));

            txtMsg.Text = sb.ToString();

  映射类

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

  

AutoMapper使用总结,布布扣,bubuko.com

时间: 2024-09-28 22:07:05

AutoMapper使用总结的相关文章

使用AutoMapper实现Dto和Model的自由转换(上)

在实际的软件开发项目中,我们的"业务逻辑"常常需要我们对同样的数据进行各种变换.例如,一个Web应用通过前端收集用户的输入成为Dto,然后将Dto转换成领域模型并持久化到数据库中.另一方面,当用户请求数据时,我们又需要做相反的工作:将从数据库中查询出来的领域模型以相反的方式转换成Dto再呈现给用户.有时候我们还会面临更多的数据使用需求,例如有多个数据使用的客户端,每个客户端都有自己对数据结构的不同需求,而这也需要我们进行更多的数据转换. 频繁的数据转换琐碎而又凌乱,很多时候我们不得不:

使用AutoMapper实现Dto和Model的自由转换(中)

在上一篇文章中我们构造出了完整的应用场景,包括我们的Model.Dto以及它们之间的转换规则.下面就可以卷起袖子,开始我们的AutoMapper之旅了. [二]以Convention方式实现零配置的对象映射 我们的AddressDto和Address结构完全一致,且字段名也完全相同.对于这样的类型转换,AutoMapper为我们提供了Convention,正如它的官网上所说的: 引用 AutoMapper uses a convention-based matching algorithm to

使用AutoMapper实现Dto和Model的自由转换(下)

书接上文.在上一篇文章中我们讨论了使用AutoMapper实现类型间1-1映射的两种方式--Convention和Configuration,知道了如何进行简单的OO Mapping.在这个系列的最后一篇文章我想基于我们的需求讨论一些中级别的话题,包括:如何实现类型体型之间的映射,以及如何为两个类型实现多个映射规则. [四]将一个类型映射为类型体系 先回顾一下我们的Dto和Model.我们有BookDto,我们有Author,每个Author有自己的ContactInfo.现在提一个问题:如何从

对象映射工具AutoMapper介绍

AutoMapper是用来解决对象之间映射转换的类库.对于我们开发人员来说,写对象之间互相转换的代码是一件极其浪费生命的事情,AutoMapper能够帮助我们节省不少时间. 一. AutoMapper解决了什么问题? 要问AutoMapper解决了什么问题? 难道不是对象映射转换的问题吗? 当然是,不过我们可以问深入一些,为什么项目中会出现大量的对象映射转换?(以下对于非MVC项目也适用) 在现代的软件开发中,项目的层级更加的细分,而不同层级之间对于对象的需求是有区别的,这就需要在不同层级间传递

0.AutoMapper

AutoMapper是基于约定的对象 - 对象映射器.AutoMapper使用流畅的配置API来定义对象 - 对象映射策略.AutoMapper使用基于约定的匹配算法来匹配源到目标值.AutoMapper面向模型投影场景,将复杂的对象模型变成DTO和其他简单对象,这些对象的设计更适合于序列化,通信,消息传递或简单的域和应用程序层之间的防腐层. 1.扁平化 2.投影 3.配置验证 4.列表和数组 5.嵌套映射 6.自定义类型转换器 7.自定义值解析器 8.空替换 9.映射操作之前和之后 10.依赖

AutoMapper的介绍与使用(二)

AutoMapper的匹配 1,智能匹配 AutoMapper能够自动识别和匹配大部分对象属性: 如果源类和目标类的属性名称相同,直接匹配,不区分大小写 目标类型的CustomerName可以匹配源类型的Customer.Name 目标类型的Total可以匹配源类型的GetTotal()方法 2,自定义匹配 Mapper.CreateMap<CalendarEvent, CalendarEventForm>()                                          

升级AutoMapper后遇到的“Missing map”与“Missing type map configuration or unsupported mapping”问题

前几天发现 AutoMapper 3.3 的一个性能问题(详见:遭遇AutoMapper性能问题:映射200条数据比100条慢了近千倍),于是将 AutoMapper 升级至最新的 5.1.1 看是否也存在这个性能问题. 升级中想当然地将之前的map配置代码: Mapper.CreateMap<AEntity, ADto>(); Mapper.CreateMap<BEntity, BDto>(); 改为: Mapper.Initialize(cfg => cfg.Create

遭遇AutoMapper性能问题:映射200条数据比100条慢了近千倍

今天遇到了AutoMapper的一个性能问题,使用的是AutoMapper的Project特性,AutoMapper版本是3.3.0,代码如下: return await _repository .GetByStartId(startIngId, itemCount) .Project() .To<TDto>() .ToListAsync(); 当获取包含200条数据的列表时,竟然超过5秒. GetDocs(3000, 200) 6304ms GetDocs(3000, 200) 5822ms

分享一个简单程序(webApi+castle+Automapper+Ef+angular)

前段时间在周末给朋友做了一个小程序,用来记录他们单位的一些调度信息(免费,无版权问题).把代码分享出来.整个程序没有做任何架构.但是麻雀虽小,用到的技术也没少.WebApi+Castle+AutoMapper+Ef+angular,日志记录Log4net.初学者可以学习借鉴,虽然做的比较仓促,但是自我感觉代码写的还是比较规范. git地址:https://git.oschina.net/richieyangs/TaskRecord.git 只需修改web.config中的连接字符串,Ctrl+F

无名小卒AutoMapper的大显神威

最近在做gxpt(高校平台的项目),前台框架用的是MVC,后台用的是EF+WCF.怎么突然说出来感觉很高大上的样子.呵呵!但是在写代码的时候就发现一个问题.就是在EF中的实体(Model)跟前台需要的实体(DTO数据传输对象)是不一样的,所以就需要转换一下.一开始也没多想,可能是被做项目的热情冲昏了头脑,写多少代码都不觉得类,所以每当需要转换的时候就一个一个的写!给大家看一个例子! <span style="font-size:18px;">namespace testau