当前位置:网站首页>[colorful] Net dto mapping
[colorful] Net dto mapping
2022-06-13 00:12:00 【PowerDon】
Let's suppose a scenario , use EF Core+Web Api, This may happen EF Core Medium Entity Model And used in the project Model There is a deviation in the corresponding relationship between , Code up
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; }
}We can observe that , There are many differences between the two entities , Like name splitting , Date of birth and age, etc , What I did before was to force handwritten code conversion , But after studying the code of the big guys , Found a class library , Here is a record
AutoMapper.Extensions.Microsoft.DependencyInjection
Can pass Nuget install
It is also very simple to use , establish Profile Folder , Create a new one EmployeeProfie class , Inherited from 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));
}
}This is the only way to use it , Inject mapper, Then there is a very simple operation , It's just , Very powerful !!!
[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);
}
}
边栏推荐
- Enterprise wechat H5_ Authentication, PC website, enterprise wechat scanning code, authorized login
- 机加工行业MES系统模具行业MES系统CNCl中工行业MES系统MES扫码报工MES数据采集
- 测试平台系列(97) 完善执行case部分
- Introduction to business rules service on SAP Business Technology Platform (BTP)
- [hcie discussion] STP-A
- PMP test experience
- [matlab] basic knowledge
- 分公司能与员工签劳动合同么
- Start blogging
- VHDL programming experiment exercises collection
猜你喜欢

PMP training organization

MASA Auth - 从用户的角度看整体设计

支持Canvas的Leaflet.Path.DashFlow动态流向线

Talent Weekly - 5

PLC也能制作小游戏----Codesys编写猜数字小游戏

Machining Industry MES system Mold Industry MES system CNCl Medium Industry MES System MES code scanning and reporting MES data collection

【HCIE论述】STP-A

【Matlab】三维曲线与三维曲面

Basic operations of dict and set

Is the newly graduated college student taking BEC or PMP? PM who wants to transfer to another job in the future
随机推荐
2022-06-13日报: 图灵奖得主:想要在学术生涯中获得成功,需要注意哪些问题?
PMP renewal | PDU specific operation diagram
Design MySQL table structure for message queue to store information data
Tsinghua Bosch joint ml center, thbi lab:cheng Yang Ying | realize safety reinforcement learning through the value at risk of constraints
在 Golang 中构建 CRUD 应用程序
[hcie discussion] STP-A
How to quickly query the mobile phone number home and operator
Distributed lock implementation
How about opening a securities account in flush? Is it safe or not
2022施工員-設備方向-通用基礎(施工員)操作證考試題及模擬考試
How to quickly query the online status of mobile phones
如何快速查询手机号码归属地和运营商
The difference between caching and buffering
Accelerating with Dali modules
Start of u-boot_ Armboot analysis (II)
[matlab] matrix transformation and matrix evaluation
[matlab] basic knowledge
How to publish OSM maps locally and customize the mapping
leaflet如何优雅的展示重叠点位的气泡窗口
3、 Storage system