【问题标题】:AutoMapper: Mapping between DTO and EntityAutoMapper:DTO 和实体之间的映射
【发布时间】:2021-06-15 22:38:54
【问题描述】:

我正在使用 ASP.NET Core WebAPI,我想为我的名为“Item”的对象执行 CRUD。 我正在使用 EF Core 处理 SQL 数据库,并且我有两个代表我的对象的模型。

  1. ItemDto - 项目的数据传输对象
  2. ItemEntity - 数据库对象(表示表格中的一行 1:1)

我的 HTTP GET one 和 HTTP GET many 方法以这样的方式工作

  1. 获取 ItemRepository 实例

  2. 获取一个或多个ItemEntity

  3. 使用 AutoMapper 将其映射到 ItemDto 这是在我的构造函数中初始化的,例如

    m_itemDtoMapper = new Mapper(new MapperConfiguration(cfg => cfg.CreateMap<ItemEntity, ItemDto>()));
    

在我的 WebAPI 方法中,我使用以下行将它映射到 ItemDto(对于 GET 很多情况):

var itemDtos = m_itemDtoMapper.Map<IEnumerable<ItemEntity>, ICollection<ItemDto>>(items);

这很好用,而且 AutoMapper 非常强大。我现在的问题是:

  1. 这是管理数据库实体和数据传输对象之间关系的标准方法吗?
  2. 在 CreateItem 方法中,我需要做反向映射。我需要将 ItemDto 映射到 ItemEntity,而不是将 ItemEntity 映射到 ItemDto。我该怎么做?仅使用切换实体创建我的映射器的副本是可行的,但它应该如何完成?即两个映射器。

【问题讨论】:

  • 不要使用m_作为前缀,C#下划线就够了:)

标签: c# asp.net-core asp.net-web-api .net-core automapper


【解决方案1】:

在您的示例中,您似乎每次都初始化一个新的映射器实例。我建议您使用依赖注入并使用 AutoMapper 映射配置文件。

您可以通过三个简单的步骤来完成,我认为它可以回答您的两个问题:

第 1 步: 只需创建一个名为 MappingProfile 或类似的新类:

   public class MappingProfile: Profile
    {
        public MappingProfile()
        {
            CreateMap<User, AuthenticateDto>(); // One Way
            CreateMap<User, UserDto>().ReverseMap(); // Reverse
        }
    }

第 2 步:在 Startup.cs 中注册 Automapper

   // Register AutoMapper
   services.AddAutoMapper(Assembly.GetExecutingAssembly());

第 3 步:通过 DI 使用您的映射器

  public UserService(IMapper mapper) {
   _mapper = mapper;
  }
// call it as you already did
_mapper.Map<User, UserDto>(user);

希望对你有所帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2012-11-08
    相关资源
    最近更新 更多