【发布时间】:2011-05-31 08:44:29
【问题描述】:
我有一个使用实体框架的数据访问层 (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;
}
【问题讨论】:
-
你能举一些你试图避免编写的重复代码的例子,以及它夹在中间的对象吗?
-
你的dtos和entities有什么区别吗?
-
是的。实体是实体对象,DTO 是 POCO。它们具有相同的参数,但 POCO 具有类似于可以创建实体的集合的 POCO 集合。
-
不要写重复的代码,就是这样
标签: c# design-patterns automapper architectural-patterns