.netCore之Automapper映射封装

1.Automapper解说
Automapper是一个对象与对象的关系映射库,目的就是帮助你实现源类型到目标类型的对象之间的映射

2.Automapper的封装
A.中间件中添加注册

点击查看代码
 //Automapper映射
 builder.Services.AddAutoMapper(typeof(AutoMapperConfigs));
B.添加特性公共类获取数据源类型与目标类型
点击查看代码
    //定义了一个特性类  命名方式:特性名+Attribute
    //特性:加注释
    //步骤1:定义特性类
    //步骤2:构建自定义特性 
    [AttributeUsage(AttributeTargets.Class)]//指定应用目标:类
    public class AutoMapperAttribute : Attribute
    {
        public Type Sourse { get; set; }
        public Type Des { get; set; }
        /// <summary>
        /// 获取源和目标类型
        /// </summary>
        /// <param name="source"></param>
        /// <param name="des"></param>
        public AutoMapperAttribute(Type source, Type des)
        {
            Sourse = source;
            Des = des;
        }
    }
C.添加对象映射公共类
点击查看代码
    /// <summary>
    /// Dto的映射配置
    /// </summary>
    public class AutoMapperConfigs: Profile
    {
        public AutoMapperConfigs()
        {
            #region 非封装下:每队源类和目标类需要一一添加映射关系,扩展性差
            //用户
            //CreateMap<User, UserRes>();
            #endregion

            #region  封装映射实现:反射+特性
            //获取程序集
            var assembly =Assembly.Load("Model");
            var list = new List<Type>();
            //遍历程序集下的类型
            foreach(var item in assembly.GetTypes())
            {
                //判断该类型是否标记AutoMapperAttribute特性
                if (item.IsDefined(typeof(AutoMapperAttribute), true))
                {
                    var type=item.GetCustomAttribute<AutoMapperAttribute>();
                    Type source = type.Sourse;
                    Type des = type.Des;
                    //源数据与目标数据的映射
                    CreateMap(source, des);
                }
            }
            #endregion
        }
    }
D.service里面注册IMapper对象
点击查看代码
        private readonly IMapper _mapper;
        public UserAppService(IMapper mapper)
        {
            _mapper = mapper;
        }
E.调用
点击查看代码
        public async Task<UserRes> GetUser(string name,string password)
        {
            var user = new User()
            {
                Id=1,
                Name = "Test",
                NickName = "Test",
                Password = "Test",
                IsEnable = true,
                UserType = 1,
                UserName="sde"
            };
            return await Task.FromResult(_mapper.Map<UserRes>(user));
        }
F.集合怎么映射 其实只需要初始化一个类到类之间的转换就行了无须继续考虑其他的,在调用的地方直接传入映射类型即可,如下:
点击查看代码
        public async Task<List<UserRes>> GetUsers2()
        {
            var list = new List<User>() {
                new User
                {
                    Name = "Test",
                    NickName = "Test",
                    Password = "Test",
                    IsEnable = true,
                    UserType=1
                },
                new User
                {
                    Name = "Test1",
                    NickName = "Test1",
                    Password = "Test1",
                    IsEnable = true,
                    UserType=1
                }
            };
            return await Task.FromResult(_mapper.Map<List<UserRes>>(list));
        }
G.AutoMapper支持的类型 集合、数组、对象、基础类型
posted @   浮生若梦cmr  阅读(187)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示