# .Net Core Dto映射(AutoMapper) 我們假設一個場景, 採用EF Core+Web Api, 這時候可能會出現EF Core中的Entity Model和在項目中使用的Model之間對應關係出現偏差, 如果使用屬性意一一對應, 不免會有大量的工作量, 上代碼 EntityMo... ...
.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);
}
}