In this part I will show how we can use a customer value formatter (CustomFormatter) to format our mapped data into single “Number of Order:” and plural “Number of Orders:”.
First the Domain and Dto (data transfer object)
//Domain
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 NumberOfOrderDto
{
public string CustomerName { get; set; }
public string NumberOfOrders { get; set; }
}
Now we will introduce a CustomResolver and Formatter, for the Formatter we are inheriting from IValueFormatter
//Resolver
public class CustomOrderCount: ValueResolver
{
protected override int ResolveCore(Order source)
{
return source.LineItems.Count();
}
}
//Formatter
public class FormatOrderCount: IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
int num = (int)context.SourceValue;
if (num
For our mapping code we will use a block for options, so that after resolving the value, it would format it.
public ActionResult NumberOfOrders()
{
var orders = _respository.GetAll();
orders.First().LineItems = new List();
Mapper.CreateMap()
.ForMember(dest => dest.NumberOfOrders, opt =>
{
opt.ResolveUsing();
opt.AddFormatter();
});
var model = Mapper.Map, IEnumerable>(orders);
return View(model);
}
//View
NumberOfOrders
@foreach (var order in Model)
{
@order.CustomerName
@order.NumberOfOrders
}
From the view we can see that the first order is displaying Order rather than Orders.
In the last part of the series I will show how to move all your mapping code to startup, so that it would speed things up.
Previous Post
Part 1 (NullSubsitution)
Part 2 (Flattening by Convention)
Part 3 (Nested Mapping)
Part 4 (Projection)
Part 5 (CustomResolver)
View Comments (2)
where is 7 out of 7?
http://taswar.zeytinsoft.com/automapper-mapping-objects-part-7-of-7-startup-registration/