What is AutoMapper

AutoMapper is a small, simple library that solves a seemingly complex problem: getting rid of manually mapping one object to another. This kind of property assignment code is repetitive and boring—AutoMapper is the tool that automates object mapping.

Object-to-object mapper: Converts an input object of one type into an output object of another type.

AutoMapper has a built-in set of convention rules. As long as the target class follows naming conventions, mapping between two types can be done with almost zero configuration.

Writing mapping code by hand is tedious, and testing it is even more so. AutoMapper provides simple type configuration and also supports unit testing of mapping logic.

Installation

Install via the NuGet Package Manager Console

PM> Install-Package AutoMapper

Companion Extension Packages

  1. AutoMapper.Data: ADO.NET support, allows mapping from IDataReader
  2. AutoMapper.EF6: Extension methods for EF6, provides asynchronous ProjectTo projection
  3. AutoMapper.Collection: Collection equivalence mapping, supports comparing two collections and performing object equality comparison
  4. AutoMapper.Collection.EF: Combines with EF primary keys for equality判断, automatically handles add/update/delete of collections, enabling persistence from DTO collections to database entity collections

Traditional Manual Object Assignment Example

Two classes People (source) and Person (target) with exactly the same property names

class People
{
    public int Age { set; get; }
    public string Name { set; get; }
}

class Person
{
    public int Age { set; get; }
    public string Name { set; get; }
}Code language: JavaScript (javascript)

Traditional approach: manually assign each property one by one:

static void Main(string[] args)
{
    People p = new People() { Age = 13, Name = "Jack" };
    Person person = new Person();

    // Manually copy every property; when there are many properties, the code becomes very verbose
    person.Name = p.Name;
    person.Age = p.Age;

    Console.WriteLine(person.Name);
    Console.WriteLine(person.Age);
    Console.ReadKey();
}Code language: JavaScript (javascript)

Drawbacks: The more properties there are, the more repetitive assignment code; when adding/modifying fields, all assignment code must be updated accordingly, and it’s easy to miss something and introduce bugs.

What AutoMapper does: It replaces the manual writing of a bunch of xxx.Property = yyy.Property statements, automatically copying same-named properties according to conventions.

What is AutoMapper

Leave a Reply

Your email address will not be published. Required fields are marked *