AutoMapper 可以很方便完成数据对象之间的转换。
Dto -> Entity
Entity -> ViewModel
Step 1:通过 NuGet 安装 AutoMapper 的包。
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="AutoMapper" Version="9.0.0" /> <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" /> </ItemGroup> </Project>
准备两个类 User 和 Department
public class User { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Remark { get; set; } public int DepartmentId { get; set; } public Department DepartmentInfo { get; set; } }
public class Department { public int Id { get; set; } public string Name { get; set; } public string Remark { get; set; } }
创建 User 的 Dto 和 ViewModel
public class UserDto { public int Id { get; set; } public string Name { get; set; } }
public class UserViewModel { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Remark { get; set; } public int DepartmentId { get; set; } public string DepartmentName { get; set; } }
Step 2:配置好对象之间的转换。
创建类 UserMapper 继承抽象类 Profile
public class UserMapper : Profile { public UserMapper() { CreateMap<UserDto, User>(); CreateMap<User, UserViewModel>() .BeforeMap((u, v) => u.Remark = "Good") .ForMember(v => v.DepartmentId, u => u.MapFrom(user => user.DepartmentId)) .ForMember(v => v.DepartmentName, u => u.MapFrom(user => user.DepartmentInfo.Name)) .AfterMap((u, v) => u.Age++); } }
Profile 里面实现了两个接口
Step 3:注册服务
在 Startup.cs 的 ConfigureServices 方法中注册。
public void ConfigureServices(IServiceCollection services) { // ... services.AddAutoMapper(typeof(UserMapper)); // ... }
Step 4:使用
创建 api 控制器
声明 private readonly IMapper _mapper;
[Route("api/[controller]/[action]")] [ApiController] public class UserController : ControllerBase { private readonly IMapper _mapper; public UserController(IMapper mapper) { _mapper = mapper; } [ActionName("dto")] [HttpGet] public IActionResult DtoToEntity() { var userDto = new UserDto() { Id = 1, Name = "Bill" }; var userEntity = _mapper.Map<UserDto, User>(userDto); JsonResult result = new JsonResult(userEntity); return result; } [ActionName("vo")] [HttpGet] public IActionResult EntityToViewModel() { var department = new Department() { Id = 101, Name = "Market" }; var user = new User() { Id = 1, Name = "Bill", Age = 25, DepartmentId = 101, DepartmentInfo = department }; var viewModel = _mapper.Map<User, UserViewModel>(user); JsonResult result = new JsonResult(viewModel); return result; } }
结果:
Dto -> Entity
Entity -> ViewModel