AutoMapper · Quick recall Q&A
2 min readQuick recall Q&A
Use AutoMapper when mappings are mostly 1:1 and you want centralized profiles plus query projections. If mappings involve conditional branching, heavy domain logic, or large object graphs where clarity matters, hand-written mapping is safer.
Profiles group mapping configuration per aggregate or feature, keeping conventions together and discoverable. They can be scanned automatically via AddAutoMapper, ensuring new mappings only require adding a profile class.
.ProjectTo<T>() with EF Core?It translates mapping expressions into SQL so the database returns DTO-shaped data directly, eliminating extra materialization and reducing memory usage in the API layer.
Use .ForMember(dest => dest.Property, opt => opt.MapFrom(src => src.OtherName)) or .ForPath for nested members. AutoMapper falls back to conventions for matching names but explicit configuration handles mismatches cleanly.
Call mapper.ConfigurationProvider.AssertConfigurationIsValid() during startup/tests, and enable CreateMissingTypeMaps = false so AutoMapper throws configuration errors early.
Register profiles via services.AddAutoMapper(typeof(SomeProfile)) or assembly scanning. Inject IMapper where needed; avoid static mapper instances so you respect scoped dependencies in custom value resolvers.
Map queryables using .ProjectTo<T>() to avoid per-item mapping in memory. For in-memory collections, IMapper.Map<IEnumerable<Dest>>(source) reuses configuration and executes efficiently without additional setup.
Yes, via ForMember(...).ConvertUsing(...), custom value resolvers, or type converters. Keep heavy logic in domain services; use converters for presentation formatting or simple transforms (e.g., decimal to string).
Configure Include/IncludeBase to map derived types and ensure discriminators map to correct DTOs. AutoMapper can project derived types so long as the EF model supports it.
Instantiate the mapper configuration in tests, call AssertConfigurationIsValid(), and perform sample Map/ProjectTo calls on fixture data to ensure custom resolvers behave as intended.