诺禾-.Net Core Dto映射(AutoMapper)

.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()
.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
CreateEmployeeForCompany(Guid companyId, EmployeeAddDto employee)
{
if (!await _companyRepository.CompanyExistsAsync(companyId))
{
return NotFound();
}
var entity = _mapper.Map(employee);
_companyRepository.AddEmployee(companyId, entity);
await _companyRepository.SaveAsync();
var dtoToReturn = _mapper.Map(entity);
return CreatedAtRoute(nameof(GetEmployeeForCompany), new
{
companyId = companyId,
employeeId = dtoToReturn.Id
}, dtoToReturn);
}
}

你可能感兴趣的:(诺禾-.Net Core Dto映射(AutoMapper))