zoukankan      html  css  js  c++  java
  • AutoMapper(ASP.NET MVC)

    需求:需要将Employee转换成DTO

        public class Employee
        {
            public int Age { get; set; }
            public int EmployeeNum { get; set; }
            public string Name { get; set; }
            public string Sex { get; set; }
            public string Email { get; set; }
    
        }
    
        public class EmployeeDTO
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string Email { get; set; }
        }

    上面两个类是基础,下面需要去做映射。

        public class EmployeeProfile : Profile
        {
            public EmployeeProfile()
            {
                //CreateMap<Employee, EmployeeDTO>(); 如果 Employee 和 DTO中所要映射的属性是一样的,就可以这样写。
    
                //将Employee类中的EmployeeNum 转换成 DTO中的ID
                CreateMap<Employee, EmployeeDTO>().ForMember(dest => dest.ID, opt => opt.MapFrom(src => src.EmployeeNum));//有多个的话,可以链式去写
            }
        }

    映射好了之后,需要在Application_Start方法中去初始化AutoMapper。

            protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();
                RouteConfig.RegisterRoutes(RouteTable.Routes);
    
                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfile(new EmployeeProfile());
                });
            }

    做好映射之后就可以直接使用了。

            public ActionResult Index()
            {
                List<Employee> employees = new List<Employee>() { new Employee { Age = 18, Sex = "", Email = "vichin@qisda.com", Name = "vichin", EmployeeNum = 1707107 } };
                IList<EmployeeDTO> viewModel = Mapper.Map<IList<Employee>, IList<EmployeeDTO>>(employees);
                return View();
            }

    下面是结果:

     

  • 相关阅读:
    [BZOJ 1698] 荷叶池塘
    [BZOJ 3132] 上帝造题的七分钟
    [JLOI2011] 飞行路线
    [Codeforces Round49F] Session in BSU
    [BZOJ 3036] 绿豆蛙的归宿
    CRC-16校验原理
    ubuntu下mysql的安装与配置
    【OpenCV】边缘检测:Sobel、拉普拉斯算子
    我对sobel算子的理解
    梯度算子(普通的+Robert + sobel + Laplace)
  • 原文地址:https://www.cnblogs.com/vichin/p/14037593.html
Copyright © 2011-2022 走看看