Use AutoMapper to eliminate the need to write tedious boilerplate code when mapping objects in your application. Credit: Maxiphoto / Getty Images AutoMapper is a popular object-to-object mapping library that can be used to map objects belonging to dissimilar types. As an example, you might need to map the DTOs (Data Transfer Objects) in your application to the model objects. AutoMapper saves you the tedious effort of having to manually map one or more properties of such incompatible types. To start working with AutoMapper, you should create a project in Visual Studio and then install AutoMapper. You can install AutoMapper from NuGet using the following command in the NuGet Package Manager Console window: PM> Install-Package AutoMapper Create mappings using AutoMapper An object-to-object mapper such as AutoMapper converts an input object of one type into an output object of another type. Consider the following two classes. public class AuthorModel { public int Id { get; set; } public string FirstName { get;set; } public string LastName { get; set; } public string Address { get; set; } } public class AuthorDTO { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } } The following code snippet shows how you can create a map between these two types, AuthorModel and AuthorDTO. var config = new MapperConfiguration(cfg => { cfg.CreateMap<AuthorModel, AuthorDTO>(); }); Then to perform the mapping between the types is as simple as the following piece of code shows. IMapper iMapper = config.CreateMapper(); var source = new AuthorModel(); var destination = iMapper.Map<AuthorModel, AuthorDTO>(source); An AutoMapper example Let’s now work with some data. Refer to the following piece of code that stores some data into the source object and then displays the property values in the destination object after the mapping is done. var config = new MapperConfiguration(cfg => { cfg.CreateMap<AuthorModel, AuthorDTO>(); }); IMapper iMapper = config.CreateMapper(); var source = new AuthorModel(); source.Id = 1; source.FirstName = "Joydip"; source.LastName = "Kanjilal"; source.Address = "India"; var destination = iMapper.Map<AuthorModel, AuthorDTO>(source); Console.WriteLine("Author Name: "+ destination.FirstName + " " + destination.LastName); When you execute the above piece of code, the author name stored inside the destination object will be displayed. However, the values of the destination FirstName and destination LastName properties will be the same as the source object because you have mapped the objects successfully using AutoMapper! Note that AutoMapper can map any set of classes. However, AutoMapper follows certain conventions, one of which is that the property names being mapped should have identical names. If the property names are not identical, then you must let AutoMapper know how the properties should be mapped. Assuming that we want to map the two properties Contact and ContactDetails, the following example illustrates how this can be achieved. var config = new MapperConfiguration(cfg => { cfg.CreateMap<AuthorModel, AuthorDTO>() .ForMember(destination => destination.ContactDetails, opts => opts.MapFrom(source => source.Contact)); }); Note the following statement that is used to create the destination object. var destination = iMapper.Map<AuthorModel, AuthorDTO>(source); If the destination object already exists, you can use the statement below instead. iMapper.Map(sourceObject, destinationObject); In essence, the above code snippet can be used to map two objects that already exist. Using projections in AutoMapper AutoMapper provides excellent support for projections. Projections are used to map source values to a destination that does not match the structure of the source. (By contrast, the mapping we discussed above was a one-to-one mapping.) Let’s now look at a projection. For example, consider the following class. public class Address { public string City { get; set; } public string State { get; set; } public string Country { get; set; } } Let’s have our AuthorModel class use the Address class to store address information of the authors. Here is what the updated AuthorModel class would look like. public class AuthorModel { public int Id { get; set; } public string FirstName { get;set; } public string LastName { get; set; } public Address Address { get; set; } } And here is the updated AuthorDTO class. public class AuthorDTO { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } } Now suppose we need to map the AuthorDTO and the AuthorModel classes. The following code snippet illustrates how this can be achieved. var config = new MapperConfiguration(cfg => { cfg.CreateMap<AuthorDTO, AuthorModel>() .ForMember(destination => destination.Address, map => map.MapFrom( source => new Address { City = source .City, State = source .State, Country = source.Country })); I will discuss the more advanced features of AutoMapper in a future post here. Until then, you can learn more about AutoMapper at this link. How to do more in C#: When to use an abstract class vs. interface in C# How to work with AutoMapper in C# How to use lambda expressions in C# How to work with Action, Func, and Predicate delegates in C# How to work with delegates in C# How to implement a simple logger in C# How to work with attributes in C# How to work with log4net in C# How to implement the repository design pattern in C# How to work with reflection in C# How to work with filesystemwatcher in C# How to perform lazy initialization in C# How to work with MSMQ in C# How to work with extension methods in C# How to us lambda expressions in C# When to use the volatile keyword in C# How to use the yield keyword in C# How to implement polymorphism in C# How to build your own task scheduler in C# How to work with RabbitMQ in C# How to work with a tuple in C# Exploring virtual and abstract methods in C# Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos