使用AutoMapper进行转换

Cra*_*aig 2 c# automapper

我目前在我的MVC项目中手动执行DTO => ViewModel转换.所以,代码看起来像这样:

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)
            };
Run Code Online (Sandbox Code Playgroud)

LandingModel看起来像这样:

public class LandingModel
{
    public string FamilyName { get; set; }
    public string LoggedInUser { get; set; }
    public string TimeZoneName { get; set; }
    public string CurrentDateTime { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我如何处理CurrentDateTime?它是模型中的一个字符串,通过从会话变量获取用户时区日期时间并应用字符串格式来处理.

我怎么能这样做呢 Mapper.Map<SessionToken>(model));

注意,.GetSessionDate()只需要采用UTC日期,并添加用户时区的偏移量,以根据它们提供当前日期.

wdo*_*jos 7

您可以MapperConfiguration按照以下指示处理此方案:

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));
   });
Run Code Online (Sandbox Code Playgroud)

参考:

AutoMapper - 地图操作之前和之后