.Net Core Dto映射(AutoMapper)
我们假设一个场景, 采用EF Core+Web Api, 这时候可能会出现EF Core中的Entity Model和在项目中使用的Model之间对应关系出现偏差, 如果使用属性意一一对应, 不免会有大量的工作量, 上代码
EntityModels.Employee.cs
public class Employee
{
public Guid Id { get; set; }
public Guid CompanyId { get; set; }
public string EmployeeNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Gender Gender { get; set; }
public DateTime DateOfBirth { get; set; }
public Company Company { get; set; }
}
Models.EmployeeDto.cs
public class EmployeeDto
{
public Guid Id { get; set; }
public Guid CompanyId { get; set; }
public string EmployeeNo { get; set; }
public string Name { get; set; }
public string GenderDisplay { get; set; }
public int Age { get; set; }
}
我们可以观察到, 两个实体之间有很多不同的地方, 比如名字拆分啊, 出生日期和年龄啊等等, 我之前的做法就是硬生生手写代码转换, 但是经过学习大佬们的代码, 发现了一个类库, 在此算是记录一下吧
AutoMapper.Extensions.Microsoft.DependencyInjection
可以通过NuGet安装
使用的时候也非常简单, 建立Profile文件夹, 新建一个EmployeeProfile类, 继承于Profile
public class EmployeeProfile: Profile
{
public EmployeeProfile()
{
CreateMap<Employee, EmployeeDto>()
.ForMember(dest => dest.Name,
opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
.ForMember(dest => dest.GenderDisplay,
opt => opt.MapFrom(src => src.Gender.ToString()))
.ForMember(dest => dest.Age,
opt => opt.MapFrom(src => DateTime.Now.Year - src.DateOfBirth.Year));
}
}
在使用的时候只需要这样, 注入mapper, 然后就是很简单的操作了, 简直了, 功能非常强大!!!
[ApiController]
[Route("api/companies/{companyId}/employees")]
public class EmployeesController: ControllerBase
{
private readonly IMapper _mapper;
private readonly ICompanyRepository _companyRepository;
public EmployeesController(IMapper mapper, ICompanyRepository companyRepository)
{
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
_companyRepository = companyRepository ?? throw new
ArgumentNullException(nameof(companyRepository));
}
[HttpPost]
public async Task<ActionResult<EmployeeDto>>
CreateEmployeeForCompany(Guid companyId, EmployeeAddDto employee)
{
if (!await _companyRepository.CompanyExistsAsync(companyId))
{
return NotFound();
}
var entity = _mapper.Map<Employee>(employee);
_companyRepository.AddEmployee(companyId, entity);
await _companyRepository.SaveAsync();
var dtoToReturn = _mapper.Map<EmployeeDto>(entity);
return CreatedAtRoute(nameof(GetEmployeeForCompany), new
{
companyId = companyId,
employeeId = dtoToReturn.Id
}, dtoToReturn);
}
}
来源:oschina
链接:https://my.oschina.net/u/4410409/blog/3301650