现在有2个实体(A、B),2个实体中的部分字段是相同的,现在把A实体获取的值赋值给B实体,利用AutoMapper实体映射可以轻松解决

参考

实体中不同名称之间的映射可以这样写

Mapper.Initialize(x =>
            x.CreateMap<WorldA, WorldB>()
             .ForMember(d => d.AGE, opt => {
             opt.MapFrom(s => s.name);
           })
           );

注意:字段名称相同的类型一定也要相同不然会报错的

AutoMapper.3.2.1\lib\net40

//第一步初始化
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<WorldA, WorldB>();
            });
List
<WorldA> worldAs = new List<WorldA>() { new WorldA() { id = 1, wewe = "测试1",name="98k" }, new WorldA() { id = 2, wewe = "测试2",name="98k" }, new WorldA() { id = 3, wewe = "测试3",name="98k" }, }; //A实体值赋给B实体 List<WorldB> b = Mapper.Map<List<WorldA>, List<WorldB>>(worldAs).ToList();
 public class WorldA
        {
            public int id { get; set; }
            public string wewe { get; set; }

            public string name { get; set; }
        }
        public class WorldB
        {
            public int id { get; set; }
            public string wewe { get; set; }

            public string AGE { get; set; }

 public string money { get; set; } }

 值为null的处理

 Mapper.Initialize(x => x.AddProfile<UserProfile>());
            List<WorldA> worldAs = new List<WorldA>()
            {
               new WorldA() { id = 1, wewe = "测试1",name=null },
               new WorldA() { id = 2, wewe = "测试2",name="98k" },
               new WorldA() { id = 3, wewe = "测试3",name="98k" },
            };  
            
            //A实体值赋给B实体
            List<WorldB> b = Mapper.Map<List<WorldA>, List<WorldB>>(worldAs).ToList();
public class UserProfile : Profile { protected override void Configure() { CreateMap<WorldA, WorldB>() .ForMember(d => d.AGE, opt => opt.MapFrom(s => s.name)) .ForMember(d => d.AGE, opt => opt.NullSubstitute("值为空") ); CreateMap<WorldA, WorldB>() .ForMember(d => d.money, opt => opt.MapFrom(s => s.name)) .ForMember(d => d.money, opt => opt.NullSubstitute("值为空") ); } }

 

 

posted on 2019-08-21 17:11  红磨坊后的白桦树  阅读(316)  评论(0编辑  收藏  举报