AutoMapper in ASP.NET Core + Reverse Mapping

AutoMapper in ASP.NET Core + Reverse Mapping

In this blog, I demonstrate how to use AutoMapper in an ASP.NET Core MVC application with a clear, complete example. I also show manual mapping to help you understand the differences. Watch the full tutorial on YouTube and download the reference PDF.

📺 Watch the Video Tutorial

📄 Download the PDF Guide

Download: AutoMapper in ASP.NET Core MVC (PDF)

🧾 Full C# Code

using System;
using AutoMapper;

namespace StudentMappingApp
{
    // Domain Model
    public class Student
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime DOB { get; set; }
        public string Class { get; set; }
        public string Address { get; set; }
    }

    // DTO
    public class StudentDTO
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public int Age { get; set; }
        public string Class { get; set; }
        public string Address { get; set; }
    }

    // Manual Mapping
    public static class ManualMapper
    {
        public static StudentDTO Convert(Student student)
        {
            return new StudentDTO
            {
                Id = student.Id,
                FullName = $"{student.FirstName} {student.LastName}",
                Age = CalculateAge(student.DOB),
                Class = student.Class,
                Address = student.Address
            };
        }

        private static int CalculateAge(DateTime dob)
        {
            var today = DateTime.Today;
            int age = today.Year - dob.Year;
            if (dob > today.AddYears(-age)) age--;
            return age;
        }
    }

    // AutoMapper Profile
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap()
                .ForMember(dest => dest.FullName,
                    opt => opt.MapFrom(src => $"{src.FirstName} {src.LastName}"))
                .ForMember(dest => dest.Age,
                    opt => opt.MapFrom(src => CalculateAge(src.DOB)))
                .ReverseMap()
                .ForMember(dest => dest.FirstName,
                    opt => opt.MapFrom(src => GetFirstName(src.FullName)))
                .ForMember(dest => dest.LastName,
                    opt => opt.MapFrom(src => GetLastName(src.FullName)))
                .ForMember(dest => dest.DOB,
                    opt => opt.Ignore()); // Cannot derive DOB from Age
        }

        private int CalculateAge(DateTime dob)
        {
            var today = DateTime.Today;
            int age = today.Year - dob.Year;
            if (dob > today.AddYears(-age)) age--;
            return age;
        }

        private static string GetFirstName(string fullName)
        {
            if (string.IsNullOrWhiteSpace(fullName)) return "";
            return fullName.Split(' ')[0];
        }

        private static string GetLastName(string fullName)
        {
            if (string.IsNullOrWhiteSpace(fullName)) return "";
            var parts = fullName.Split(' ');
            return parts.Length > 1 ? parts[^1] : "";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var student = new Student
            {
                Id = 1,
                FirstName = "John",
                LastName = "Doe",
                DOB = new DateTime(2005, 6, 10),
                Class = "10th Grade",
                Address = "123 Main St"
            };

            Console.WriteLine("\n=== AutoMapper Mapping ===");
            var config = new MapperConfiguration(cfg => cfg.AddProfile());
            var mapper = config.CreateMapper();
            var autoDto = mapper.Map(student);
            PrintDTO(autoDto);

            // Map StudentDTO → Student
            var mappedBackStudent = mapper.Map(autoDto);
            Console.WriteLine("\n=== AutoMapper Reverse Mapping ===");
            Console.WriteLine($"FirstName: {mappedBackStudent.FirstName}");
            Console.WriteLine($"LastName: {mappedBackStudent.LastName}");
            Console.WriteLine($"Class: {mappedBackStudent.Class}");
            Console.WriteLine($"Address: {mappedBackStudent.Address}");
            Console.WriteLine($"DOB: {mappedBackStudent.DOB} (Ignored in reverse map)");

            Console.ReadKey();
        }

        static void PrintDTO(StudentDTO dto)
        {
            Console.WriteLine($"Id: {dto.Id}");
            Console.WriteLine($"FullName: {dto.FullName}");
            Console.WriteLine($"Age: {dto.Age}");
            Console.WriteLine($"Class: {dto.Class}");
            Console.WriteLine($"Address: {dto.Address}");
        }
    }
}

📞 Contact Me for 1-to-1 .NET Training

I offer personalized one-to-one .NET training sessions (C#, ASP.NET Core, Web API, Entity Framework and more).

WhatsApp/Call: +91-9331897923

Website: supernovaservices.com

Class Guidelines for Effective 1-on-1 Learning

To keep every session productive and distraction-free, please follow these simple guidelines:

  • Quiet Environment: Join from a calm, private room with minimal background noise. Avoid public or noisy places.
  • No Interruptions: Inform family/roommates in advance. Keep doors closed during class.
  • Mobile on Silent / DND: Set your phone to Silent or Do Not Disturb to prevent calls and notifications.
  • Be Fully Present: Do not multitask. Avoid attending to other calls, visitors, or errands during the session.
  • Stable Setup: Use a laptop/desktop with a stable internet connection and required software installed (Visual Studio/.NET, SQL Server, etc.).
  • Punctuality: Join on time so we can utilize the full session effectively.
  • Prepared Materials (If any): Keep project files, notes, and questions ready for quicker progress.

Following these guidelines helps you focus better and ensures I can deliver the best learning experience in every class.

Schedule a Quick 10-Minute Call

I prefer to start with a short 10-minute free call so I can understand:

  • Your learning objectives and career goals
  • Your current skill level
  • The exact topics you want to learn

Why? Because course content, teaching pace, and fees all depend on your needs — there’s no “one-size-fits-all” pricing. Please leave your details below, and I’ll get back to you to arrange a convenient time for the call.



Google Review Testimonials

.NET Online Training
Average Rating: 4.9
Votes: 50
Reviews: 50