AutoMapper is a mapping tool for use in .NET. It is used to translate data from one object to another, most often to and from complex objects to simple objects such as DTOs. AutoMapper eliminates the repetitive code and provides an easy mechanism of how properties from the source object map to the destination object.
Reduces Repetitive Code: You don’t need to map properties manually, AutoMapper does that for you.
Improves Code Readability: In other words, it is used to abstract away mapping logic and this makes your code cleaner and easier to understand.
Consistent Mapping: Saves a lot of test writing, because you know exactly how the same objects will map.
Less Error-Prone: It reduces human error by automating property assignments.
Easily Configurable: For some cases (combining properties or calculating properties) you can define custom mappings.
Speeds Up Development: It saves time so you don’t have to write the code that transforms this object over and over again.
Supports Complex Mappings: It is easily able to handle complicated mapping scenarios (e.g. nested objects, collection).
Improves Testability: It separates mapping logic from business logic making your code more testable.
Step 1: Install AutoMapper NuGet Package
Install the required NuGet packages:
dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
Step 2 : Define the Source and Destination Classes
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Currency { get; set; }
public List<string> Tags { get; set; }
public decimal DiscountPercentage { get; set; }
}
public class ProductDto
{
public int Id { get; set; }
public string Name { get; set; }
public string PriceWithCurrency { get; set; }
public string Tags { get; set; }
public decimal DiscountedPrice { get; set; }
}
Step 3: Create a Custom Mapping Profile
public class CustomMappingProfile : Profile
{
public CustomMappingProfile()
{
CreateMap<Product, ProductDto>()
.ForMember(dest => dest.PriceWithCurrency,
opt => opt.MapFrom(src => $"{src.Price} {src.Currency}"))
.ForMember(dest => dest.Tags,
opt => opt.MapFrom(src => string.Join(", ", src.Tags)))
.ForMember(dest => dest.DiscountedPrice,
opt => opt.MapFrom(src => src.Price - (src.Price * src.DiscountPercentage / 100)));
}
}
Step 4: Configure AutoMapper in the Application
var builder = WebApplication.CreateBuilder(args);
// Add AutoMapper
builder.Services.AddAutoMapper(typeof(CustomMappingProfile));
var app = builder.Build();
app.Run();
This demonstrates the flexibility and power of AutoMapper for handling custom mapping scenarios.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our .Net Expertise.
0