C# AutoMapper 利用特性进行实体间的映射

AutoMapper:6.2.2.0

案例:UserDto和User实体之间的映射(User类除了Name拥有更多字段)

    [AutoMap(typeof(User))]
    public class UserDto {
        public string Name { get; set; }
    }

最后直接使用:var userDto = userService.Find("001").MapTo<UserDto>(); 完成映射

自定义特性:

1.映射方向,也就是Api中CreateMap 从哪映射到哪。

    public enum AutoMapDirection
    {
        From,
        To
    }

2.映射自定义特性

    

public class AutoMapAttribute : Attribute
    {
        public Type[] TargetTypes { get; private set; }

        internal virtual AutoMapDirection Direciton
        {
            get { return AutoMapDirection.From | AutoMapDirection.To; }
        }

        public AutoMapAttribute(params Type[] targetTypes)
        {
            TargetTypes = targetTypes;
        }
    }

    public class AutoMapFromAttribute : AutoMapAttribute
    {
        internal override AutoMapDirection Direciton
        {
            get { return AutoMapDirection.From; }
        }
        public AutoMapFromAttribute(params Type[] targetTypes)
            :base(targetTypes)
        {

        }
    }

    public class AutoMapToAttribute : AutoMapAttribute
    {
        internal override AutoMapDirection Direciton
        {
            get { return AutoMapDirection.To; }
        }
        public AutoMapToAttribute(params Type[] targetTypes)
            : base(targetTypes)
        {

        }
    }

3.映射帮助类,进行注册,初始化。

    public class AutoMapperProfile : Profile
    {
        private static Dictionary<Type, Type> mapDics = new Dictionary<Type, Type>();
        public AutoMapperProfile()
        {
            foreach (var key in mapDics.Keys)
            {
                CreateMap(key, mapDics[key]);   //创建映射关系
            }
        }
        /// <summary>
        /// 添加映射
        /// </summary>
        /// <param name="sourceType">源类型</param>
        /// <param name="destinationType">目标类型</param>
        public static void AddMapping(Type sourceType,Type destinationType)
        {
            mapDics.Add(sourceType, destinationType);
        }
    }

    public class AutoMapperHelper
    {
        public static void CreateMap(Type type)
        {
            CreateMapping<AutoMapFromAttribute>(type);
            CreateMapping<AutoMapToAttribute>(type);
            CreateMapping<AutoMapAttribute>(type);
        }

        public static void Register()
        {
            Mapper.Initialize(x => x.AddProfile<AutoMapperProfile>());      //最后初始化注册一次
        }

        private static void CreateMapping<TAttribute>(Type type)
            where TAttribute : AutoMapAttribute
        {
            if (!type.IsDefined(typeof(TAttribute)))
            {
                return;
            }

            foreach (var autoMapAttr in type.GetCustomAttributes<TAttribute>())
            {
                if (autoMapAttr.TargetTypes.IsNullOrEmpty())
                {
                    continue;
                }

                foreach (var targetType in autoMapAttr.TargetTypes)
                {
                    if (autoMapAttr.Direciton.HasFlag(AutoMapDirection.To))
                    {
                        AutoMapperProfile.AddMapping(type, targetType);
                    }
                    if (autoMapAttr.Direciton.HasFlag(AutoMapDirection.From))
                    {
                        AutoMapperProfile.AddMapping(targetType, type);
                    }
                }
            }
        }
    }

使用:

        static void Main(string[] args)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var allTypes = new List<Type>();
            allTypes.AddRange(assembly.GetTypes().Where(type => type != null));
            foreach (var type in allTypes)
            {
                AutoMapperHelper.CreateMap(type);
            }
            AutoMapperHelper.Register();  //创建映射完毕后进行注册
            var userDto = rList.First().MapTo<UserDto>();
        }



©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页