AutoMapper:给定类型的IValueFormatter的网站广泛使用 [英] AutoMapper : Site wide usage of IValueFormatter for given types

查看:222
本文介绍了AutoMapper:给定类型的IValueFormatter的网站广泛使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的理解,我可以按照以下方式配置AutoMapper,在映射期间,应该将所有源模型日期格式化为IValueFormatter中定义的规则,并将结果设置为映射模型。

It is my understanding I can configure AutoMapper in the following way and during mapping it should format all source model dates to the rules defined in the IValueFormatter and set the result to the mapped model.

ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();
ForSourceType<DateTime?>().AddFormatter<StandardDateFormatter>();

我使用this对我的映射类没有效果。它只有在我执行以下操作时才有效:

I get no effect for my mapped class with this. It only works when I do the following:

Mapper.CreateMap<Member, MemberForm>().ForMember(x => x.DateOfBirth, y => y.AddFormatter<StandardDateFormatter>());

我映射 DateTime? Member.DateOfBirth 更改为 string MemberForm.DateOfBirth 。格式化程序基本上从日期创建了一个短的日期字符串。

I am mapping DateTime? Member.DateOfBirth to string MemberForm.DateOfBirth. The formatter basically creates a short date string from the date.

在为给定类型设置默认格式化程序时,我缺少什么?

Is there something I am missing when setting the default formatter for a given type?

感谢

public class StandardDateFormatter : IValueFormatter
{
    public string FormatValue(ResolutionContext context)
    {
        if (context.SourceValue == null)
            return null;

        if (!(context.SourceValue is DateTime))
            return context.SourceValue.ToNullSafeString();

        return ((DateTime)context.SourceValue).ToShortDateString();
    }
}


推荐答案

I有同样的问题,并找到一个修复。尝试更改:

I had the same problem and found a fix. Try changing:

ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();

Mapper.ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();

这篇关于AutoMapper:给定类型的IValueFormatter的网站广泛使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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