SoFunction
Updated on 2025-03-06

How to use AutoMapper in C#

Translation link:/art...

AutoMapper is a very popular object-to-object mapping library. Its purpose is to help you achieve mapping between objects of different types. For example, in the DDD development model, you may need to map DTO object to Model object. In the past, you needed to map the attribute fields under these two types one by one. Now AutoMapper can help you save the time spent on this redundant template-style code matching.

Before you start playing AutoMapper, you need to create a Project in Visual Studio and install AutoMapper. You can download it from NuGet or enter the following command in the NuGet Package Manager Console console:

PM> Install-Package AutoMapper

Create mapping relationships using AutoMapper

An object-to-object mapping tool like AutoMapper must be able to convert one input type to another output type. Isn't it difficult to talk about? You can first 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;
    }
  }

Next, the following code snippet will tell you how to use AutoMapper to create a mapping relationship between AuthorModel and AuthorDTO.

var config = new MapperConfiguration(cfg => {
        <AuthorModel, AuthorDTO>();
      });

For the final mapping conversion, you need to add a few sentences of the following code to implement the conversion between the two types.

IMapper iMapper = ();
var source = new AuthorModel();
var destination = <AuthorModel, AuthorDTO>(source);

An example of AutoMapper

Next, we can upload some data. You can refer to the code snippet below. I plan to assign values ​​on the source object first, and then execute the Map method in AutoMapper, and then display it as it is on the destination object.

var config = new MapperConfiguration(cfg => {
        <AuthorModel, AuthorDTO>();
      });
IMapper iMapper = ();
var source = new AuthorModel();
 = 1;
 = "Joydip";
 = "Kanjilal";
 = "India";
var destination = <AuthorModel, AuthorDTO>(source);
("Author Name: "+  + " " + );

After you execute this code, the Author Name on the destination object will be output to the console. The two attribute values ​​of FirstName on the destination object are consistent, indicating that the automapper has helped you successfully map.

It is worth noting that AutoMapper can not only map one class, but also map multiple classes. By default, AutoMapper will match according to the default convention, that is, the same attribute names between the objects being mapped can be successfully mapped. However, in reality, many mapped attribute names are different. At this time, you need to manually intervene in specifying the mapping relationship and let AutoMapper execute according to the execution you set, assuming that you need to implement the mapping between Contact and ContactDetails. The following example shows how to implement this relationship.

var config = new MapperConfiguration(cfg => {
        <AuthorModel, AuthorDTO>()
        .ForMember(destination => ,
        opts => (source => ));
      });

The following statement creates the final destination object object.

var destination = <AuthorModel, AuthorDTO>(source);

Sometimes you have generated destination object, and on this basis you also want to map quadraticly, you can use the following alternative statement.

(sourceObject, destinationObject);

Essentially, the above code is often used to match two existing objects.

Using AutoMapping's projects feature

AutoMapper provides very good projects function. The part of projects 🐂👃 is that when mapping, you can ignore whether the object data structures of the two can be consistent. For example, let multiple attributes of source map onto one attribute of destination, and what we have been discussing above is one-to-one object mapping.

Next, let’s learn about projection together, give an example, consider the following categories.

  public class Address
  {
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
  }

Next, an Address property is added to the AuthorModel class to store the Author's address information. The modified AuthorModel class is as follows:

  public class AuthorModel
  {
    public int Id
    {
      get; set;
    }
    public string FirstName
    {
      get;set;
    }
    public string LastName
    {
      get; set;
    }
    public Address Address
    {
      get; set;
    }
  }

Then update the 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; }
  }

Next we need to map AuthorDTO to AuthorModel. The following code snippet shows how to implement it.

var config = new MapperConfiguration(cfg => {
        <AuthorDTO, AuthorModel>()
          .ForMember(destination => ,
       map => (
         source => new Address
         {
           City = source .City,
           State = source .State,
           Country = 
         }));

I will continue to discuss more advanced features of AutoMapper in a subsequent article, and now you can use this link:/Learn more about AutoMapper.

For more high-quality information: See my GitHub:dotnetfly

The above is the detailed content of how to use AutoMapper in C#. For more information about the use of C# AutoMapper, please follow my other related articles!