In Part 5, we will use a powerful feature that automapper allows us, which is CustomResolver.
Lets look at our Domain Object which contains a boolean field called ShipToHomeAddress, what we will do is map those boolean to a string value with “Yes” or “No”.
public class Order
{
public string OrderNo { get; set; }
public Customer Customer { get; set; }
public DateTime PurchaseDate { get; set; }
public IEnumerable LineItems { get; set; }
public bool ShipToHomeAddress { get; set; }
public decimal GetTotal()
{
return LineItems == null ? 0 : LineItems.Sum(x => x.GetTotalPrice());
}
public Guid InternalId { get; set; }
}
//DTO
public class OrderShipDto
{
public string ShipHome { get; set; }
public string CustomerName { get; set; }
}
For our mapping code we will introduce CustomResolver class which inherits from ValueResolver and would map the boolean field to string
public class CustomBoolResolver: ValueResolver
{
protected override string ResolveCore(Order source)
{
return source.ShipToHomeAddress ? "Yes" : "No";
}
}
Now our mapping code would look like
public ActionResult OrderShip()
{
var orders = _respository.GetAll();
Mapper.CreateMap()
.ForMember(dest => dest.ShipHome, opt => opt.ResolveUsing());
var model = Mapper.Map, IEnumerable>(orders);
return View(model);
}
//View
OrderShip
Name | Ship to Home |
---|---|
@item.CustomerName | @item.ShipHome |
The end result of the view looks like
In Part6, I will show how to use a CustomerFormatter with a Resolver to format the data in a certain way.
Previous Post:
Part 1 (NullSubsitution)
Part 2 (Flattening by Convention)
Part 3 (Nested Mapping)
Part 4 (Projection)
View Comments (1)
Automapper 6 - ValueResolver is no more there.