AutoMapper:针对给定类型的IValueFormatter的站点范围使用

CRi*_*ice 1 configuration automapper

我可以通过以下方式配置AutoMapper,在映射过程中,它应将所有源模型日期格式化为IValueFormatter中定义的规则,并将结果设置为映射模型.

ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();
ForSourceType<DateTime?>().AddFormatter<StandardDateFormatter>();
Run Code Online (Sandbox Code Playgroud)

我对我的映射类没有任何影响.它仅在我执行以下操作时有效:

Mapper.CreateMap<Member, MemberForm>().ForMember(x => x.DateOfBirth, y => y.AddFormatter<StandardDateFormatter>());
Run Code Online (Sandbox Code Playgroud)

我正在映射DateTime?Member.DateOfBirth to String MemberForm.DateOfBirth.格式化程序基本上从日期创建一个短日期字符串.

在为给定类型设置默认格式化程序时,是否存在我缺少的内容?

谢谢

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

小智 5

我有同样的问题,并找到了解决方案.尝试改变:

ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();
Run Code Online (Sandbox Code Playgroud)

Mapper.ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();
Run Code Online (Sandbox Code Playgroud)