TechieClues TechieClues
Updated date Apr 03, 2023
In this article, we will explore how to use Automapper in an ASP.NET Core project with sample code and explanation.

Introduction:

Automapper is an open-source object-to-object mapping library that simplifies the process of mapping one object to another. It is widely used in ASP.NET Core projects and provides an easy way to map entities to DTOs (Data Transfer Objects) and vice versa. In this article, we will explore how to use Automapper in an ASP.NET Core project.

Installing Automapper

The first step is to install Automapper using NuGet Package Manager. Open your project in Visual Studio and go to the "Manage NuGet Packages" option from the "Tools" menu. Search for "AutoMapper" and install the latest version.

Alternatively, you can install it via Package Manager Console by running the following command:

Install-Package AutoMapper

Setting up AutoMapper

After installing the package, we need to configure Automapper in our project. In ASP.NET Core, we can do this in the ConfigureServices method in the Startup.cs file. Add the following code to the method:

services.AddAutoMapper(typeof(Startup));

This will configure AutoMapper for our project and register all mapping profiles in the assembly.

Creating Mapping Profiles

Now that we have set up AutoMapper, we need to create mapping profiles that define how the mapping should be done. A mapping profile is a class that inherits from Profile and contains the mapping configuration.

Let's create a mapping profile for a simple example. Consider the following two classes:

public class Customer
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

public class CustomerDto
{
    public int Id { get; set; }
    public string FullName { get; set; }
    public string Email { get; set; }
}

We want to map Customer to CustomerDto by concatenating FirstName and LastName into FullName. Let's create a mapping profile for this:

public class CustomerProfile : Profile
{
    public CustomerProfile()
    {
        CreateMap<Customer, CustomerDto>()
            .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"));
    }
}

In this profile, we use the CreateMap method to create a mapping between Customer and CustomerDto. We then use the ForMember method to specify that FullName should be mapped to the concatenation of FirstName and LastName.

Using AutoMapper

Now that we have set up AutoMapper and created a mapping profile, we can use it in our code. Let's say we have a Customer object:

var customer = new Customer
{
    Id = 1,
    FirstName = "John",
    LastName = "Doe",
    Email = "[email protected]"
};

We can map it to a CustomerDto object like this:

var customerDto = _mapper.Map<CustomerDto>(customer);

Here, _mapper is an instance of IMapper that is injected into our class. AutoMapper uses the mapping profile we created earlier to map the Customer object to a CustomerDto object.

Mapping Collections

Automapper also provides support for mapping collections of objects. Let's say we have a list of Customer objects:

var customers = new List < Customer > {
  new Customer {
    Id = 1, FirstName = "John", LastName = "Doe", Email = "[email protected]"
  },
  new Customer {
    Id = 2, FirstName = "Jane", LastName = "Doe", Email = "[email protected]"
  }
};

We can map this list to a list of `CustomerDto` objects like this:

var customerDtos = _mapper.Map<List<CustomerDto>>(customers);

This will create a new list of CustomerDto objects by mapping each Customer object in the customers list.

Ignoring Properties

Sometimes we may want to ignore certain properties while mapping objects. For example, if we have a CustomerDto object with a Password property that we don't want to map from the Customer object. We can ignore this property using the ForMember method:

CreateMap<Customer, CustomerDto>()
    .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
    .ForMember(dest => dest.Password, opt => opt.Ignore());

Here, we use the Ignore method to specify that the Password property should not be mapped.

Conclusion

In this article, we have explored how to use Automapper in an ASP.NET Core project. We learned how to install the package, set up AutoMapper, create mapping profiles, and use AutoMapper to map objects. We also looked at how to map collections and ignore properties during mapping. AutoMapper simplifies the process of mapping objects and reduces the amount of boilerplate code required for object mapping in ASP.NET Core projects.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!