实体属性映射框架 【AutoMapper】 的使用

安装方法:使用vs自带的nuget管理工具,搜索AutoMapper ,选择第一个安装到你的项目即可。

 

AutoMapper 的使用分为两种:

1. 可自动映射到目标实体

   源实体与目标实体的字段名字是一致的,源实体的字段可以与目标实体中的字段数量不一致。

   源实体中的字段名字是Getxxx,而目标实体中对应的字段也可以是xxx。

   源实体中包含的实体类字段为Sub,里面包含的字段名字为Age,那么目标实体中对应的字段名字可以是:SubAge。

源实体:

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

        public string GetA { set; get; }
        public string GetD { set; get; }


        public string SetB { set; get; }

        public string c { set; get; }

        public SubSource1 Sub { set; get; }
    }


    public class SubSource1
    {
        public string Age { set; get; }

    }

目标实体:

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

        public string A { set; get; }

        public string C { set; get; }

        public string SubAge { set; get; }

        public string D { set; get; }
    }

封装的扩展方法:

        public static TDestination MapTo<TSource, TDestination>(this TSource source)
            where TDestination : class
            where TSource : class
        {
            if (source == null) return default(TDestination);
            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<TDestination>(source);
        }

        public static IEnumerable<TDestination> MapToList<TSource, TDestination>(this IEnumerable<TSource> source)
            where TDestination : class
            where TSource : class
        {
            if (source == null) return new List<TDestination>();
            var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>());
            var mapper = config.CreateMapper();
            return mapper.Map<List<TDestination>>(source);
        }

调用方法:

    var source1 = new Source1
    {
        Name = "source",
        Sub = new SubSource1 { Age = "25" },
        c = "C",
        GetA = "A",
        SetB = "B"
    };
    var destViewModel = source1.MapTo<Dest1, Source1>();

2. 需要配置才能映射到目标实体

    var config2 = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>()
            .ForMember(d => d.DestName, opt => opt.MapFrom(s => s.Name))  //指定字段一一对应
            .ForMember(d => d.Birthday, opt => opt.MapFrom(s => s.Birthday.ToString("yy-MM-dd HH:mm"))) //指定字段按指定的格式转化
            .ForMember(d => d.Age, opt => opt.Condition(s => s.Age > 5))  //满足条件才赋值
            .ForMember(d => d.A1, opt => opt.Ignore())  //忽略该字段,不给该字段赋值
            .ForMember(d => d.A2, opt => opt.NullSubstitute("Default Value"))  //如果源字段值为空,则赋值为 Default Value
            .ForMember(d => d.A3, opt => opt.MapFrom(s => s.Name + s.Age * 3 + s.Birthday.ToString("d"))) //自己随意组合赋值
    );
 *****************************
 *** Keep learning and growing. ***
 *****************************
原文地址:https://www.cnblogs.com/gangle/p/9269574.html