自动映射器格式化程序不起作用 [英] Automapper Formatter not working

查看:77
本文介绍了自动映射器格式化程序不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将格式化程序添加到我的Automapper配置中,以设置所有DateTime?字段的样式.我尝试过在全球范围内添加格式化程序:

I'm trying to add a formatter to my Automapper configuration to style all DateTime? fields. I've tried adding my formatter globally:

Mapper.AddFormatter<DateStringFormatter>();

关于特定的映射本身:

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

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

But neither seems to work - it always outputs the date in the normal format. For reference, here is the ViewModel I'm using, and the rest of the configuration:

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

PostViewModel:

PostViewModel:

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

我在做什么错了?

谢谢!

推荐答案

仅当目标成员类型为字符串"类型时才应用格式符.由于发布"的类型为"DateTime?",因此格式化程序永远不会应用.您在这里有几个选择:

Formatters are only applied when the destination member type is of type "string". Since "Published" is of type "DateTime?", the formatter never gets applied. You have a few options here:

  • 将行为添加到Post对象,其行为如上所述.
  • 为发布"属性创建一个自定义解析器,该解析器首先解析DateTime?属性逻辑中的值,然后在发布时将目标成员类型更改为字符串.首先,解析器将执行.接下来,格式化程序获取自定义解析程序的结果,最后,将结果值设置为发布的"
  • 使用HtmlHelper之类的方法在视图中完成所有自定义Type->字符串格式

我们通常进行1),除非显示的值仅真正针对该视图,否则我们进行选项2).

We usually go for 1), unless the value displayed is truly only for this view, then we go for option 2).

这篇关于自动映射器格式化程序不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆