What is AutoMapper in ASP.NET Core and its Usage?

What is AutoMapper in ASP.NET Core and its Usage?

14 Jun 2024
Intermediate
140 Views
7 min read
Learn via Video Course & by Doing Hands-on Labs

Self-Paced ASP.NET Core Course

AutoMapper in .NET Core

Using object-to-object mappings in your ASP.NET application is a process that many times proves to be difficult. This is where AutoMapper can be helpful as it simplifies this process while reducing boilerplate code.

Let's get to know what AutoMapper is with this ASP.NET Tutorial, how it is used, and why it is so essential in the .NET Core ecosystem. Learn more about other core concepts related to ASP.NET in detail through our ASP.NET Certification Training.

Read More: Top Features of ASP.NET

What is AutoMapper?

AutoMapper is a simple, yet powerful library that allows you to automatically link one object to another. This becomes particularly helpful when one has dissimilar models, like data transfer objects (DTOs) and view models to be transformed in and out of domain models. Through minimal configuration, AutoMapper handles these conversions, so that you can save time and reduce the chance of errors.
What is AutoMapper?

How to Use AutoMapper in Our Application?

Using AutoMapper in your ASP.NET Core Application is pretty easy. Let’s get to know the steps involved.

1. Installation

In the beginning, you need to install the NuGet package called AutoMapper. This can either be done by the package manager in the visual studio or through running the given command in the package manager console:

Install-Package AutoMapper

2. Configuration

After setting up the software, carry out the configuration of AutoMapper to enable it to run within the application. This is typically done in the Startup.cs file for ASP.NET Core applications.
public void ConfigureServices(IServiceCollection services)
{
    // Auto Mapper Configurations
    var mapperConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new MappingProfile());
    });

    IMapper mapper = mapperConfig.CreateMapper();
    services.AddSingleton(mapper);
    services.AddMvc();
}

3. Usage

Once configured, you can use AutoMapper to map objects in your application. Here’s a simple example:
public class Source
{
    public int Value { get; set; }
}

public class Destination
{
    public int Value { get; set; }
}

public class MyService
{
    private readonly IMapper _mapper;

    public MyService(IMapper mapper)
    {
        _mapper = mapper;
    }

    public Destination GetMappedObject(Source source)
    {
        return _mapper.Map<Destination>(source);
    }
}

4. Profiles

Profiles are a way to organize your mapping configurations. Instead of configuring mappings in Startup.cs, you can create separate profile classes.
public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Source, Destination>();
    }
}

5. Use AutoMapper in Your Services or Controllers:

public class MyController : ControllerBase
{
    private readonly IMapper _mapper;

    public MyController(IMapper mapper)
    {
        _mapper = mapper;
    }

    public IActionResult Get()
    {
        var source = new Source();
        var destination = _mapper.Map<Destination>(source);
        return Ok(destination);
    }
}
Read More: Top 50 ASP.NET Core Interview Questions and Answers for 2024

Creating Rules for Mapping Properties With Different Names

Sometimes, the source and destination objects might have properties with different names. AutoMapper allows you to create rules to handle these scenarios:
CreateMap<Source, Destination>()
    .ForMember(dest => dest.DifferentName, opt => opt.MapFrom(src => src.OriginalName));
/pre>

Reverse Mapping

AutoMapper also supports reverse mapping, which means you can map from the destination object back to the source object using the ReverseMap method:
CreateMap<Source, Destination>().ReverseMap();

Why Do We Need AutoMapper in .NET Core?

Using AutoMapper in .NET Core applications brings several benefits:
  • Reduces Boilerplate Code- AutoMapper reduces the amount of code needed to map properties between objects.
  • Enhances Maintainability- With centralized mapping configurations, maintaining and updating mappings becomes easier.
  • Improves Code Readability- AutoMapper makes the code cleaner and more readable by abstracting the mapping logic.

Usage Guidelines and Best Practices

  • Use Profiles- Organize your mappings into profiles for better maintainability.
  • Avoid Complex Mappings- Keep your mappings simple. For complex scenarios, consider using custom resolvers.
  • Test Your Mappings- Ensure you write unit tests for your mappings to avoid runtime issues.
  • Stay Updated- Keep your AutoMapper package up to date to benefit from the latest features and fixes.
Conclusion
Just follow these simple steps as discussed above, and you can easily integrate AutoMapper into your applications. By doing this, you will make them more maintainable and readable in ASP.Net core. To explore various other topics from ASP.NET Development, enroll in our ASP.NET Certification Course right now!

FAQs

Q1. What is AutoMapper in .net core?

AutoMapper in .NET Core is a library that helps to mapping of properties among different kinds of object models.

Q2. What is the function of the AutoMapper?

AutoMapper helps in simplifying the process of transferring the data between different models like DTOs and domain models.

Q3. When should you use AutoMapper?

AutoMapper is required for simplification of object mapping with similar patterns like mapping Data Transfer Objects (DTOs) to domain models.

Q4. Is Mapster better than AutoMapper?

Mapster is actually a better choice as it is faster and lightweight as compared to AutoMapper.

Take our Aspnet skill challenge to evaluate yourself!

In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

GET FREE CHALLENGE

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
ASP.NET Core Certification Training Jul 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 17 MON, WED, FRI
Filling Fast
07:00AM to 08:30AM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this