gpt4 book ai didi

Automapper 格式化程序不工作

转载 作者:行者123 更新时间:2023-12-01 22:45:22 25 4
gpt4 key购买 nike

我正在尝试将格式化程序添加到我的 Automapper 配置以设置所有 DateTime? 字段的样式。我已经尝试在全局范围内添加我的格式化程序:

Mapper.AddFormatter<DateStringFormatter>();

以及具体映射本身:

Mapper.CreateMap<Post, PostViewModel>()
.ForMember(dto => dto.Published, opt => opt.AddFormatter<DateStringFormatter>());

但似乎都不起作用 - 它总是以正常格式输出日期。作为引用,这是我正在使用的 ViewModel 以及其余配置:

public class DateStringFormatter : BaseFormatter<DateTime?>
{
protected override string FormatValueCore(DateTime? value)
{
return value.Value.ToString("d");
}
}

public abstract class BaseFormatter<T> : IValueFormatter
{
public string FormatValue(ResolutionContext context)
{
if (context.SourceValue == null)
return null;

if (!(context.SourceValue is T))
return context.SourceValue == null ? String.Empty : context.SourceValue.ToString();

return FormatValueCore((T)context.SourceValue);
}

protected abstract string FormatValueCore(T value);
}

后 View 模型:

public int PostID { get; set; }
public int BlogID { get; set; }
public string UniqueUrl { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string BodyShort { get; set; }
public string ViewCount { get; set; }
public DateTime CreatedOn { get; set; }

private DateTime? published;
public DateTime? Published
{
get
{
return (published.HasValue) ? published.Value : CreatedOn;
}
set
{
published = value;
}
}

我做错了什么?

谢谢!

最佳答案

格式化程序仅在目标成员类型为“字符串”类型时应用。由于“Published”是“DateTime?”类型,因此永远不会应用格式化程序。您在这里有几个选择:

  • 将 Published 属性添加到 Post 对象,行为如上所示
  • 为 Published 属性创建自定义解析器,首先解析 DateTime?来自属性逻辑的​​值,然后在发布时将目标成员类型更改为字符串。首先,解析器将执行。接下来,格式化程序获取自定义解析器的结果,最后,将结果值设置为已发布
  • 使用 HtmlHelper 之类的东西在 View 中执行所有自定义类型 -> 字符串格式化

我们通常选择 1),除非显示的值确实仅适用于此 View ,否则我们选择选项 2)。

关于Automapper 格式化程序不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1652749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com