Craig Craig - 11 months ago 90
C# Question

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

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

Answer Source

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));


AutoMapper - Before and after map actions