Add AutoMapper to your project using the NuGet Package Manager in Visual Studio. Search for "AutoMapper" and install the first available package.
Understanding AutoMapper Field Mapping
AutoMapper provides intelligent field mapping between source and destination objects. The mapping behavior follows specific patterns that reduce boilerplate code significantly.
When property names match exactly between source and destination types, AutoMapper handles the mapping automatically. You can also map properties with different names using conventions like getter methods (GetXxx maps to Xxx) and nested properties (Sub.Age maps to SubAge).
Consider the following source entity with various property naming patterns:
public class NestedEntity { public int Age { get; set; } }
</div>The corresponding destination view model maps these properties using AutoMapper's conventions:
<div>```
public class DestinationModel
{
public string Name { get; set; }
public string Code { get; set; }
public string Value { get; set; }
public string Description { get; set; }
public string SubAge { get; set; }
}
Create an extension method to encapsulate the mapping configuration for scenarios where property names align:
var configuration = new MapperConfiguration(config =>
config.CreateMap<TSource, TDestination>());
var mapper = configuration.CreateMapper();
return mapper.Map<TDestination>(source);
}
}
</div>Usage example:
<div>```
var sourceEntity = new SourceEntity
{
Name = "sample",
Details = new NestedEntity { Age = 25 },
Description = "test",
GetCode = "CODE001",
SetIdentifier = "ID123"
};
var viewModel = sourceEntity.ConvertTo<SourceEntity, DestinationModel>();
When property names don't match or require transformation, configure explicit mappings with additional options:
var mapper = configuration.CreateMapper();
</div>The configuration supports several common mapping patterns:
- **Explicit field mapping** - Map source properties to destination properties with different names
- **Format transformations** - Convert data types and apply formatting during mapping
- **Conditional mapping** - Apply mapping only when specific conditions are met
- **Property ignore** - Exclude certain properties from being mapped
- **Null substitution** - Provide default values when source properties are null
- **Custom expressions** - Combine multiple source properties into a single destination value
Collection Mapping Extension
----------------------------
For mapping collections of objects, create a separate extension method:
<div>```
public static IEnumerable<TDestination> ConvertToList<TSource, TDestination>(
this IEnumerable<TSource> source)
where TDestination : class
where TSource : class
{
if (source == null)
return new List<TDestination>();
var configuration = new MapperConfiguration(config =>
config.CreateMap<TSource, TDestination>());
var mapper = configuration.CreateMapper();
return mapper.Map<List<TDestination>>(source);
}
var secondEntity = new SourceEntity { Name = "sample2", Details = new NestedEntity { Age = 30 }, Description = "second", GetCode = "A002", SetIdentifier = "B002" };
var entityCollection = new List<SourceEntity> { firstEntity, secondEntity }; var viewModelCollection = entityCollection.ConvertToList<SourceEntity, DestinationModel>();
</div>Best Practices
--------------
AutoMapper excels at reducing repetitive mapping code between domain entities and view models. For complex mapping scenarios with custom transformtaions, the fluent configuration API provides fine-grained control. Consider caching mapper instances in production scenarios to avoid repeated configuration overhead.
</div>