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

发布于 2024-10-09 19:50:45 字数 746 浏览 0 评论 0原文

我有一个使用实体框架的数据访问层(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云胡 2024-10-16 19:50:45

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

I would use code generation to generate the repetitive code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文