AutoMapper
public class Student { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public DateTime date { set; get; } } public class StudentDTO { public int Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string date { set; get; } } public class StudentActivityDTO { public int Id { get; set; } public string Name { get; set; } public string Age { get; set; } public string datetime { set; get; } }
public class StudentProfile : Profile { protected override void Configure() { //Student->StudentDTO //CreateMap<Student, StudentDTO>(); //Student->StudentDTO CreateMap<Student, StudentDTO>() .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id)) .ForMember(d => d.Name, opt => opt.MapFrom(s => s.Name)) .ForMember(d => d.Age, opt => opt.MapFrom(s => s.Age.ToString() + " 岁")) .ForMember(d => d.date, opt => opt.MapFrom(s => string.Format("{0:yyyy-MM-dd}", s.date))); //Student->StudentActivityDTO CreateMap<Student, StudentActivityDTO>() .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id)) .ForMember(d => d.Name, opt => opt.MapFrom(s => s.Name)) .ForMember(d => d.Age, opt => opt.MapFrom(s => s.Age.ToString() + " 岁")) .ForMember(d => d.datetime, opt => opt.MapFrom(s => string.Format("{0:yyyy-MM-dd}", s.date))); } }
Mapper.CreateMap<Source, Destination>(); //直接依据字段名转换两个类
Student stu = new Student() { Id = 1, Name = "2", Age = 12, date = DateTime.Now }; StudentDTO stu_dto = Mapper.Map<StudentDTO>(stu);