DTO操作案例



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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值