Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
What is AutoMapper in ASP.NET Core and its Usage?

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

07 Aug 2024
Intermediate
2.31K Views
7 min read
Learn with an interactive course and practical hands-on labs

Free 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

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

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

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

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
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this