DTO操作案例

来源:互联网 发布:ios 大众点评 源码 编辑:程序博客网 时间:2024/05/16 03:40


using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DTOTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.Initialize(m => m.AddProfile<MapperProfile>());

            //Entity Model
            UserInfo user = new UserInfo();
            user.Name = "xiaoqiu";
            user.Age = 21;
            user.Address = "湖北襄阳";
            user.Birth = new DateTime(1995, 8, 18);

            //DTO: Data Transfer Object    AutoMapper 6.0以下版本
            //UserInfo_DTO user_dto = Mapper.Map<UserInfo_DTO>(user);
            //Console.WriteLine(user_dto.Name);
            //Console.WriteLine("出生年:" + user_dto.Birth_Year + "年" + user_dto.Birth_Month + "月");
            //Console.Read();

            //DTO: Data Transfer Object    AutoMapper 6.0以下版本
            var config = new MapperConfiguration(cfg => cfg.CreateMap<UserInfo, UserInfo_DTO>());
            IMapper mapp = config.CreateMapper();
           
            UserInfo_DTO user_dto = mapp.Map<UserInfo_DTO>(user);
            Console.WriteLine(user_dto.Name);
            Console.WriteLine("出生年:" + user_dto.Birth_Year + "年" + user_dto.Birth_Month + "月");
            Console.Read();
        }
    }

    public class MapperProfile : Profile
    {
        //所有继承自Profile类的子类都是一个映射集合
        protected override void Configure()
        {
            CreateMap<UserInfo, UserInfo_DTO>();


            //映射,需要将出生日期映射到DTO中为年、月
            CreateMap<UserInfo, UserInfo_DTO>()
                .ForMember(dto => dto.Birth_Month, opt => opt.MapFrom(src => src.Birth.Month))
                .ForMember(dto => dto.Birth_Year, opt => opt.MapFrom(src => src.Birth.Year));
        }
    }


    /// <summary>
    /// 用户信息
    /// </summary>
    public class UserInfo
    {
        public string UserID { get; set; }
        public string UserName { get; set; }
        public string UserPwd { get; set; }
        public int Age { get; set; }
        public string Name { get; set; }
        public DateTime Birth { get; set; }
        public string Address { get; set; }
        public string Tel { get; set; }
    }


    /// <summary>
    /// 用户信息DTO数据传输对象
    /// </summary>
    public class UserInfo_DTO
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public int Birth_Year { get; set; }
        public int Birth_Month { get; set; }
    }

}

0 0
原创粉丝点击