DEV Community

Juarez Júnior
Juarez Júnior

Posted on

Simplified Object Mapping with AutoMapper

AutoMapper is a popular library that allows automatic conversion of objects from one type to another. This is useful when you need to map domain objects to DTOs (Data Transfer Objects) or vice-versa, without the need to manually write code for each property. In this example, we will see how to automatically map a domain object to a DTO.

Libraries:

To use the AutoMapper library, install the NuGet package in your project:

Install-Package AutoMapper
Enter fullscreen mode Exit fullscreen mode

Example Code:

using AutoMapper;
using System;

namespace AutoMapperExample
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    public class ProductDTO
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Configuring AutoMapper
            var config = new MapperConfiguration(cfg => cfg.CreateMap<Product, ProductDTO>());
            var mapper = config.CreateMapper();

            // Creating a Product object
            Product product = new Product { Id = 1, Name = "Laptop", Price = 1500.99m };

            // Mapping Product to ProductDTO
            ProductDTO productDTO = mapper.Map<ProductDTO>(product);

            Console.WriteLine($"Name: {productDTO.Name}, Price: {productDTO.Price}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation:

In this example, we create two classes: Product and ProductDTO. The Product class contains all the properties, while the ProductDTO class contains only Name and Price. In the Main method, we configure AutoMapper to map from Product to ProductDTO. Then, we create a Product object and automatically map it to a ProductDTO object. Finally, we print the values from the ProductDTO to the console.

Conclusion:

AutoMapper simplifies the process of converting between different objects, eliminating the need to write repetitive code to map properties. It is especially useful in scenarios where you need to map domain objects to DTOs in layered applications.

Source code: GitHub

Top comments (0)