轻量级对象映射工具TinyMapper

之前使用的对象映射工具一直都是AutoMapper,前几天听公司前辈说了一下这个TinyMapper是轻量级的,执行效率比较高。昨天抽时间试了一下它的基础用法,感觉还是非常简单易懂的,今天写个小小的总结记录一下吧。

组件官网:tinymapper.net

安装方式:VS可以直接通过NuGet搜索TinyMapper即可一键安装到项目中

组件用法(需求一):将Entity的内容映射到OutEntity

    public class Entity
    {
        public string CarNumber { get; set; }
        public string Vin { get; set; }
        public string Remark { get; set; }
    }

    public class OutEntity
    {
        public Guid Id { get; set; }
        public string CarNumber { get; set; }
        public string Vin { get; set; }
        public string Remark { get; set; }
    }

    //初始化实体
    Entity entity=new Entity(){CarNumber="赣AD12345",Vin="ABCDEFG",Remark="无"};

    //绑定实体
    TinyMapper.Bind<Entity, OutEntity>();


    //映射实体
    OutEntity outEntity = TinyMapper.Map<OutEntity>(entity);

组件用法(需求二):将List<Entity>的内容映射到List<OutEntity>

    public class Entity
    {
        public string CarNumber { get; set; }
        public string Vin { get; set; }
        public string Remark { get; set; }
    }

    public class OutEntity
    {
        public Guid Id { get; set; }
        public string CarNumber { get; set; }
        public string Vin { get; set; }
        public string Remark { get; set; }
    }


    //初始化集合
    List<Entity> entitys=new List<Entity>();

    //绑定集合
    TinyMapper.Bind<List<Entity>, List<OutEntity>>();


    //映射集合
    List<OutEntity> outEntitys = TinyMapper.Map<List<OutEntity>>(entitys);

组件用法(需求三):20201013新增两种常见用法

    //对指定字段映射(初始化和执行映射与上文一致)
    TinyMapper.Bind<Product, ProductDTO>(t =>
    {
        t.Bind(a => a.Price, b=> b.Money);
    });
    //排除指定字段映射(初始化执行映射与上文一致)
    TinyMapper.Bind<Product, ProductDTO>(t=>
    {
        t.Ignore(a => a.Price); 
    });

至此,基本且常用的映射用法实例总结已经结束了,如果有不懂的小伙伴可以在本文下方留言,我将与你一起讨论。

THE END