使用自动映射器进行转换

编程入门 行业动态 更新时间:2024-10-26 21:30:52
本文介绍了使用自动映射器进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我目前在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) };

LandingModel如下所示:

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

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

如何使用Mapper.Map<SessionToken>(model));

执行此操作

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

推荐答案

您可以在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)); });

引用:

AutoMapper - Before and after map actions

更多推荐

使用自动映射器进行转换

本文发布于:2023-11-04 12:08:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557898.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!