csharp-agile-mapper

AgileMapper, a mapper for C# focused on simplicity

  • 2 min

AgileMapper is one of the most popular libraries for object mapping in C# .NET applications due to its ease of use and performance.

It is an alternative to more well-known mappers like Automapper or Mapster, following a philosophy of simplicity without sacrificing performance.

AgileMapper particularly excels when working with complex object mapping, reducing coding time.

Furthermore, it provides a wide range of configuration options to customize the object mapping behavior, which are common in any mapper library.

For example, you can set a default value for a field if it is not found in the source object, or you can specify a custom conversion for a specific field.

How to Use AgileMapper

We can easily add the library to a .NET project through the corresponding NuGet package.

Install-Package AgileObjects.AgileMapper

Once the library is installed, we can start using it in the code. For example, if we wanted to map an object of type Person to an object of type PersonViewModel, we simply do:

var person = new Person
{
    FirstName = "John",
    LastName = "Doe",
    Age = 30
};

// project to new object
var personViewModel = Mapper.Map(person).ToANew<PersonViewModel>();
Copied!

It also allows us to perform operations on collections of elements. In this case, the comparison is made by the Id property.

var source = new[]
{
    new CustomerViewModel { Id = 1,    Name = "Rod" },
    new CustomerViewModel { Id = 2,    Name = "Jane" },
    new CustomerViewModel { Id = null, Name = "Freddy" }
};
var target = Collection<Customer>
{
    new Customer { CustomerId = 1, Name = "Bungle" },
    new Customer { CustomerId = 2, Name = null },
    new Customer { CustomerId = 3, Name = "Zippy" }
};

// Update (updates the values from source to target)
var result = Mapper.Map(source).Over(target);

/// Merge (includes the values from source to target if they are null)
var result = Mapper.Map(source).OnTo(target);
Copied!

If we want to modify the mapping configuration we can use a MapperConfiguration object. For example, if we want to set a default value for a field not found in the source object, we can do the following:

var config = new MapperConfiguration(cfg => cfg
    .WhenMapping
    .From<Person>()
    .To<PersonViewModel>()
    .Map("Email")
    .To(vm => vm.EmailAddress)
    .Use("No email address provided"));

Copied!