ABP Framework — Object Mapping
ABP v10.x object mapping. The IObjectMapper abstraction; Mapperly is the default (compile-time), AutoMapper is also supported.
Trigger
"ABP object mapping", "DTO mapping", "Mapperly", "AutoMapper", "IObjectMapper".
Usage (ObjectMapper)
ObjectMapper.Map<Book, BookDto>(book);
ObjectMapper.Map<List<Book>, List<BookDto>>(books);
ObjectMapper.Map(input, book); // onto an existing destination
ObjectMapper is available in base classes; elsewhere, inject IObjectMapper.
Mapperly (default)
[Mapper]
public partial class BookMapper : MapperBase<Book, BookDto>
{
public override partial BookDto Map(Book source);
public override partial void Map(Book source, BookDto destination);
}
// Module: [DependsOn(typeof(AbpMapperlyModule))] + context.Services.AddMapperlyObjectMapper<MyModule>();
// Custom field: [MapProperty(nameof(Book.Name), nameof(BookDto.Title))]
AutoMapper (alternative)
public class MyProfile : Profile
{
public MyProfile() { CreateMap<Book, BookDto>(); CreateMap<CreateUpdateBookDto, Book>(); }
}
// Module: [DependsOn(typeof(AbpAutoMapperModule))]
// context.Services.AddAutoMapperObjectMapper<MyModule>();
// Configure<AbpAutoMapperOptions>(o => o.AddMaps<MyModule>(validate: true));
// Attribute:
[AutoMapFrom(typeof(Book))] public class BookDto : EntityDto<Guid> { }
[AutoMapTo(typeof(Book))] public class CreateBookDto { }
Best Practices
- Use the
ObjectMapperabstraction (don't depend on the provider) - Mapperly for new projects (default since v10.4)
- Keep mappings in the Application layer; use
validate: truewith AutoMapper - On create/update, only map allowed fields
Related
- DDD · API · Development Flow
- ABP Docs: https://abp.io/docs/latest/framework/infrastructure/object-to-object-mapping