/// <summary> /// 通过配置类来实现转化 /// </summary> public static void AutoMapperThree() { Mapper.Initialize(x => x.AddProfile <UserProfile>());//可以在MVC中Global中一次性注册 User user = new User() { Id = 1, Name = "caoyc", Age = 20, }; UserDto2 dto = Mapper.Map <UserDto2>(user); Console.WriteLine(dto.Age + dto.Name2); }
/// <summary> /// 如果属性名称不同 /// </summary> public static void AutoMapperTwo() { Mapper.Initialize(x => x.CreateMap <User, UserDto2>().ForMember(d => d.Name2, opt => opt.MapFrom(s => s.Name))); User user = new User() { Id = 1, Name = "caoyc", Age = 20 }; UserDto2 dto = Mapper.Map <UserDto2>(user); Console.WriteLine(dto.Age + dto.Name2); }