如何避免在映射时编写大量重复代码?
我有一个使用实体框架的数据访问层(DAL),我想使用 Automapper 与上层进行通信。我必须将数据传输对象 (DTO) 映射到实体,作为每个方法的第一个操作,处理我的输入,然后继续从实体映射到 DTO。您会做什么来跳过编写这段代码?
举个例子,看看这个:
//This is a common method in my DAL
public CarDTO getCarByOwnerAndCreditStatus(OwnerDTO ownerDto, CreditDto creditDto)
{
//I want to automatize this code on all methods similar to this
Mapper.CreateMap<OwnerDTO,Owner>();
Mapper.CreateMap<CreditDTO,Credit>();
Owner owner = Mapper.map(ownerDto);
Owner credit = Mapper.map(creditDto)
//... Some code processing the mapped DTOs
//I want to automatize this code on all methods similar to this
Mapper.CreateMap<Car,CarDTO>();
Car car = Mapper.map(ownedCar);
return car;
}
I have a data access layer (DAL) using Entity Framework, and I want to use Automapper to communicate with upper layers. I will have to map data transfer objects (DTOs) to entities as the first operation on every method, process my inputs, then proceed to map from entities to DTOs. What would you do to skip writing this code?
As an example, see this:
//This is a common method in my DAL
public CarDTO getCarByOwnerAndCreditStatus(OwnerDTO ownerDto, CreditDto creditDto)
{
//I want to automatize this code on all methods similar to this
Mapper.CreateMap<OwnerDTO,Owner>();
Mapper.CreateMap<CreditDTO,Credit>();
Owner owner = Mapper.map(ownerDto);
Owner credit = Mapper.map(creditDto)
//... Some code processing the mapped DTOs
//I want to automatize this code on all methods similar to this
Mapper.CreateMap<Car,CarDTO>();
Car car = Mapper.map(ownedCar);
return car;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会使用代码生成来生成重复的代码。
I would use code generation to generate the repetitive code.