In Part 4 we will see how we can use projection to map inner objects for example a DateTime field.
Again our domain and Dto (Data Transfer Object) looks like
//Order
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 OrderDateDto
{
public int PurchaseHour { get; set; }
public int PurchaseMinute { get; set; }
public string CustomerName { get; set; }
}
We will map the PurchaseDate in the Domain Object to our Dto PurchaseHour and Purchase Minute.
public ActionResult OrderDate()
{
var order = _respository.Get(3);
order.PurchaseDate = new DateTime(2011, 3, 15, 20, 30, 0);
Mapper.CreateMap()
.ForMember(dest => dest.PurchaseHour, opt => opt.MapFrom(src => src.PurchaseDate.Hour))
.ForMember(dest => dest.PurchaseMinute, opt => opt.MapFrom(src => src.PurchaseDate.Minute));
var model = Mapper.Map(order);
return View(model);
}
//View
OrderDate
@Model.CustomerName @Model.PurchaseHour @Model.PurchaseMinute
As you can see the View now contains the flatten Hour and Minute, from our previous posting we also see that the other way of nested projection/flattening is by CustomerName.
Here is how our view would display
In part 5, I will show how to use CustomerResolver to resolve and map values to different types.
Previous Post:
Part 1 (NullSubsitution)
Part 2 (Flattening by Convention)
Part 3 (Nested Mapping)
View Comments (3)
Hi, thank you again for your tutorial
I am facing this case
AutoMapper.Mapper.CreateMap()
.ForMember(dest => dest.UserName, src => src.MapFrom(s => s.UserName))
.ForMember(dest => dest.Age, src => src.MapFrom(s => s.Age));
.ForMember(dest => dest.Preference, src => src.MapFrom(s => new ProfilePreferenceViewData{ Language = s.language, TimeZone = s.TimeZone }))
I am wondering how to use an external mapping like this
AutoMapper.Mapper.CreateMap()
.ForMember(dest => dest.Language, src => src.MapFrom(s => s.Language))
.ForMember(dest => dest.TimeZone, src => src.MapFrom(s => s.TimeZone));
And modify the original mapping so to have
AutoMapper.Mapper.CreateMap()
.ForMember(dest => dest.UserName, src => src.MapFrom(s => s.UserName))
.ForMember(dest => dest.Age, src => src.MapFrom(s => s.Age));
.ForMember(dest => dest.Preference, src => src.MapFrom(What I created)
Hope it is clear
Funny thing is if you look at my Part 5 of this series by using a CustomResolver you can very well get that working. Just create a ValueResolver like something ValueResolver < YourType, ProfilePreferenceViewData >
http://taswar.zeytinsoft.com/2011/03/11/automapper-mapping-objects-part-5-of-7-customresolver/
I should have waited for your next tutorial...
Thank you.
I will give it a deep look