AutoMapper is an object mapping library that allows mapping of properties from an object of one type to another object of a different type. It can automatically map properties that have matching names between classes. Custom mappings can also be defined, such as mapping a flattened property or formatting properties in a custom way. AutoMapper aims to simplify object mapping between different object types.
2. Introduction
AutoMapper is an object-to-object mapper, which
allows you to solve issues with mapping of the same
properties in one object of one type to another object
of another type. For example, mapping a heavy entity
Customer object to the CustomerDTO could be done
with AutoMapper automatically.
6. Flattening
public class Customer { public Company Company { get; set; } }
public class Company { public string Name { get; set; } }
public class CustomerViewItem
{
public string CompanyName { get; set; }
}
AutoMapper goes in to the depth of your classes, and if names
match, it will do the mapping for you.
7. Custom Type Resolvers
public class Customer { public bool VIP { get; set; } }
public class CustomerViewItem { public string VIP { get; set; }
public class VIPResolver : ValueResolver<bool, string>
{
protected override string ResolveCore(bool source)
{
return source ? "Y" : "N";
}
}
.ForMember(cv => cv.VIP, m =>
m.ResolveUsing<VIPResolver>().FromMember(x => x.VIP));
8. Custom Formatters
public class DateFormatter:IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
return ((DateTime) context.SourceValue).ToLongDateString();
}
}
.ForMember(cv => cv.DateOfBirth, m =>
m.AddFormatter<DateFormatter>());