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”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class Order { public string OrderNo { get; set; } public Customer Customer { get; set; } public DateTime PurchaseDate { get; set; } public IEnumerable<OrderItems> 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
1 2 3 4 5 6 7 |
public class CustomBoolResolver: ValueResolver<Order, string> { protected override string ResolveCore(Order source) { return source.ShipToHomeAddress ? "Yes" : "No"; } } |
Now our mapping code would look like
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public ActionResult OrderShip() { var orders = _respository.GetAll(); Mapper.CreateMap<Order, OrderShipDto>() .ForMember(dest => dest.ShipHome, opt => opt.ResolveUsing<CustomBoolResolver>()); var model = Mapper.Map<IEnumerable<Order>, IEnumerable<OrderShipDto>>(orders); return View(model); } //View <h2>OrderShip</h2> <table> <tr> <th>Name</th> <th>Ship to Home</th> </tr> @foreach (var item in Model) { <tr> <td>@item.CustomerName</td> <td>@item.ShipHome</td> </tr> } </table> |
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)
[…] field called ShipToHomeAddress, what we will do is map those boolean to a string value with… [full post] taswar Taswar Bhatti Blog .netautomapper 0 0 0 0 0 […]
Automapper 6 – ValueResolver is no more there.