📎 Webclip
The Best Way To Map Objects in .Net in 2024
The post explains object mapping as a transformation between application layers and says it helps with separation of concerns, performance, security, and maintainability. It contrasts manual mapping with mapping libraries and argues that, in 2024, manual mapping is the better choice when combined with required properties.
Reading notes#
- Object mapping transforms objects from one type to another, usually between domain models and public contract models.
- DTOs are described as smaller client-facing models that can combine data from more than one domain model.
- Separate public models let the domain change without breaking API clients.
- The article presents two main mapping approaches: manual mapping and automated mapping with libraries.
- Manual mapping is shown with a
Bookentity and aBookDto, where each DTO property is assigned explicitly. - AutoMapper is presented as a popular library that uses profiles,
AddAutoMapper, andIMapper.Map. - Mapster is presented as another library, configured through
IRegister,AddMapster,TypeAdapterConfig.GlobalSettings.Scan, andAdapt. - The article says mapping libraries can add performance overhead, complex configuration, debugging difficulty, and runtime errors when profiles are not updated.
- For the main example, the article introduces
BlogPost,Publisher, andBlogHistoryRecordentities, along withBlogPostDtoandPublisherDto. - The manual mapping example uses extension methods like
MapToBlogPostDtoandMapToPublisherDto. BlogPostDtomapsIdtoUrl, convertsPublishedUtctoPublishedDate, mapsPublisherwith another method, and computesRatingfrom history records.PublisherDtomapsName, counts posts forTotalPosts, and computesRatingfrom ratings across related blog posts.- The article shows using these mapping methods in minimal API endpoints for
/api/blogsand/api/publishers. - All entity and DTO properties are marked
required, and the article treats this as the key advantage because missing a mapped property becomes a compiler error. - After adding
DescriptionandCategorytoBlogPost, the article says the application fails to compile until the mapping is updated. - The conclusion is that manual mapping with required properties is the best approach because it is explicit, compile-time safe, more performant, and easier to debug.
