c# Mapster

介绍对象:Mapster

Mapster是.Net对象映射类库,可能听过的人不多,但相信你一定听过AutoMapper,个人感觉Mapster比其跟好用,更方便,学习成本更低

github:https://github.com/MapsterMapper/Mapster

操作:

准备实体:

public class Student
    {
        public string ID { get; set; }
        public string NAME { get; set; }
        public int AGE { get; set; }
        public string CID { get; set; }
        public Cource Cource { get; set; }
    }
public class Cource
    {
        public string ID { get; set; }
        public string CourceName { get; set; }
        public double Grade { get; set; }
    }
public class StudentDto
    {
        public string ID { get; set; }
        public string NAME { get; set; }
        public string CourceName { get; set; }
    }

实战:

简单映射:字段、属性系统会默认自动映射,下图中Student对象转为StudentDto

            Cource cource = new Cource();
            cource.ID = "1";
            cource.CourceName = "数学";
            cource.Grade = 80.56;

            Student stu = new Student();
            stu.AGE = 25;
            stu.ID = "1";
            stu.CID = "321281199505290919";
            stu.NAME = "陈兆杰";
            stu.Cource = cource;
            StudentDto stuDto = new StudentDto();
            {
                //方法一:
                stuDto = stu.Adapt<StudentDto>();//stu实例映射为StudentDto类型

                //方法二:
                stu.Adapt(stuDto);//stu实例映射为stuDto实例,相同的名称字段属性将会自动映射

                //方法三:
                IMapper mapper = new Mapper();
                stuDto = mapper.Map<StudentDto>(stu);// stu实例映射为StudentDto类型

                //方法四:
                mapper.Map(stu, stuDto);//stu实例映射为stuDto实例,相同的名称字段属性将会自动映射
            }

复杂映射:上面简单映射,类StudentDto中的CourceName属性没有被映射,通过下面方法可对属性设置匹配关系,给CourceName属性映射

            Cource cource = new Cource();
            cource.ID = "1";
            cource.CourceName = "数学";
            cource.Grade = 80.56;

            Student stu = new Student();
            stu.AGE = 25;
            stu.ID = "1";
            stu.CID = "321281199505290919";
            stu.NAME = "陈兆杰";
            stu.Cource = cource;
            StudentDto stuDto = new StudentDto();
            {
                TypeAdapterConfig config = new TypeAdapterConfig();
                //建立映射关系一, NewConfig 删除任何现有配置
                {
                    config.NewConfig<Student, StudentDto>()
            .Map(dto => dto.ID, d => d.ID).Map(dto => dto.NAME, d => d.NAME).Map(dto => dto.CourceName, s => s.Cource.CourceName);
                }
                //建立映射关系二,而 ForType 创建或增强配置。
                {
            //        config.ForType<Student, StudentDto>()
            //.Map(dto => dto.ID, d => d.ID).Map(dto => dto.NAME, d => d.NAME).Map(dto => dto.CourceName, s => s.Cource.CourceName);
                }
                stuDto = stu.Adapt<StudentDto>(config);//根据config配置,映射stu实体为StudentDto类型
            }

扩展:

表达式目录树实现的Mapper,可以实现较复杂映射

/// <summary>
        /// 可以处理复杂映射
        /// </summary>
        /// <typeparam name="TIn">输入类</typeparam>
        /// <typeparam name="TOut">输出类</typeparam>
        /// <param name="expression">表达式目录树,可以为null</param>
        /// <param name="tIn">输入实例</param>
        /// <returns></returns>
        public static TOut Mapper<TIn, TOut>(TIn tIn, Expression<Func<TIn, TOut>> expression = null)
        {
            ParameterExpression parameterExpression = null;
            List<MemberBinding> memberBindingList = new List<MemberBinding>();
            parameterExpression = Expression.Parameter(typeof(TIn), "p");

            if (expression != null)
            {
                parameterExpression = expression.Parameters[0];
                if (expression.Body != null)
                {
                    memberBindingList.AddRange((expression.Body as MemberInitExpression).Bindings);
                }
            }
            foreach (var item in typeof(TOut).GetProperties())
            {
                if (typeof(TIn).GetProperty(item.Name) != null)
                {
                    MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
                if (typeof(TIn).GetField(item.Name) != null)
                {
                    MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
            }
            foreach (var item in typeof(TOut).GetFields())
            {
                if (typeof(TIn).GetField(item.Name) != null)
                {
                    MemberExpression property = Expression.Field(parameterExpression, typeof(TIn).GetField(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
                if (typeof(TIn).GetProperty(item.Name) != null)
                {
                    MemberExpression property = Expression.Property(parameterExpression, typeof(TIn).GetProperty(item.Name));
                    MemberBinding memberBinding = Expression.Bind(item, property);
                    memberBindingList.Add(memberBinding);
                }
            }
            MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(TOut)), memberBindingList.ToArray());

            Expression<Func<TIn, TOut>> lambda = Expression.Lambda<Func<TIn, TOut>>(memberInitExpression, new ParameterExpression[]
            {
                    parameterExpression
            });
            Func<TIn, TOut> func = lambda.Compile();//获取委托
            return func.Invoke(tIn);
        }

实例:

 Student stu = new Student
                {
                    age = 25,
                    id = 1,
                    name = "陈兆杰111",
                    classes = classes
                };

 StudentDto StuDto1 = ExpressionMapper.Mapper(stu, s => new StudentDto
                    {
                        classesName = s.classes.name,
                    });

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值