zoukankan      html  css  js  c++  java
  • 实体映射-------AutoMapper

    现在有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.1lib et40

    //第一步初始化
                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("值为空") ); } }

     

  • 相关阅读:
    博雅机器学习十讲1
    tensorflow学习笔记1
    卓有成效的程序员3
    卓有成效的程序员2
    卓有成效的程序员1
    探索需求6
    数据预处理
    数据科学介绍
    探索需求5
    探索需求4
  • 原文地址:https://www.cnblogs.com/macT/p/11389896.html
Copyright © 2011-2022 走看看