Craig
Craig

Reputation: 18684

Transformation using AutoMapper

I currently manually do my DTO => ViewModel transformations in my MVC project. So, the code looks like this:

var model = new LandingModel {
                FamilyName = token.FamilyName,
                LoggedInUser = token.DisplayName,
                TimeZoneName = token.TimeZoneName,
                CurrentDateTime = Common.SessionManager.GetSessionDate().ToString(SharedLib.Constants.FMT_DATE_AND_TIME_LONG)
            };

A LandingModel looks like this:

public class LandingModel
{
    public string FamilyName { get; set; }
    public string LoggedInUser { get; set; }
    public string TimeZoneName { get; set; }
    public string CurrentDateTime { get; set; }
}

How do I handle then CurrentDateTime? It's a string in the model, and is handled via by getting the users timezone date time from a session variable, and applying a string format.

How can I do this using Mapper.Map<SessionToken>(model));

Note, .GetSessionDate() simply takes UTC date, and adds an offset from the users timezone, to give the current date according to them.

Upvotes: 4

Views: 4368

Answers (1)

Wagner DosAnjos
Wagner DosAnjos

Reputation: 6374

You can handle this scenario in your MapperConfiguration as indicated below:

var config = new MapperConfiguration(
   cfg =>
   {
      cfg.CreateMap<SessionToken, LandingModel>()
         .AfterMap((src, dest) => dest.CurrentDateTime = Common.SessionManager.GetSessionDate().ToString(SharedLib.Constants.FMT_DATE_AND_TIME_LONG));
   });

REFERENCE:

AutoMapper - Before and after map actions

Upvotes: 9

Related Questions