如何避免在映射时编写大量重复代码?

时间:2010-12-27 23:22:03

标签: c# design-patterns automapper architectural-patterns

我有一个使用Entity Framework的数据访问层(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;
}

1 个答案:

答案 0 :(得分:1)

我会使用代码生成来生成重复代码。