AutoMapper : Site wide usage of IValueFormatter for given types

岁酱吖の 提交于 2020-01-16 03:43:09

问题


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

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

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?

Thanks

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

回答1:


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

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

To

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



回答2:


FYI - AddFormatter method is obsolete in 3.0 version. You can use ConvertUsing instead:

Mapper.CreateMap<DateTime, string>()
    .ConvertUsing<DateTimeCustomConverter>();

public class DateTimeCustomConverter : ITypeConverter<DateTime, string>
{
    public string Convert(ResolutionContext context)
    {
        if (context.SourceValue == null)
            return null;
        if (!(context.SourceValue is DateTime))
            return context.SourceValue.ToNullSafeString();
        return ((DateTime)context.SourceValue).ToShortDateString();
    }
}



回答3:


I am using AutoMapper v1.

There is an abstract class there that does most of the grunt work called ValueFormatter.

My Code:

public class DateStringFormatter : ValueFormatter<DateTime>
{
    protected override string FormatValueCore(DateTime value)
    {
        return value.ToString("dd MMM yyyy");
    }
}

Then in my Profile class:

public sealed class ViewModelMapperProfile : Profile
{
    ...

    protected override void Configure()
    {
        ForSourceType<DateTime>().AddFormatter<DateStringFormatter>();

        CreateMap<dto, viewModel>()
            .ForMember(dto => dto.DateSomething, opt => opt.MapFrom(src => src.DateFormatted));

}



来源:https://stackoverflow.com/questions/2779068/automapper-site-wide-usage-of-ivalueformatter-for-given-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!