AgileMapper is one of the most popular libraries for object mapping in C# in .NET applications due to its ease of use and performance.
It is an alternative to better-known mappers such as Automapper or Mapster, under a philosophy of simplicity, without sacrificing performance.
AgileMapper stands out especially when working with complex object mapping, reducing coding time and improving the quality of our code.
It also provides a large number of configuration options to customize the behavior of object mapping, 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 has been 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 have to do,
var person = new Person
{
FirstName = "John",
LastName = "Doe",
Age = 30
};
// project to new object
var personViewModel = Mapper.Map(person).ToANew<PersonViewModel>();
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);
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 that is 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"));
AgileMapper is Open Source, and all the code and documentation is available in the project’s repository at https://github.com/agileobjects/AgileMapper