AutoMapper: extensive use of the IValueFormatter site for these types

I understand that I can configure AutoMapper as follows, and during the comparison, it must format all the dates of the original model with the rules defined in IValueFormatter and set the result for the associated 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>());

Am I Matching DateTime? Member.DateOfBirth to string MemberForm.DateOfBirth . The formatter basically creates a short string of dates from the date.

Is there something that I am missing when setting the standard formatting for this type?

thank

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
3

, . :

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

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

FYI - AddFormatter 3.0. ConvertUsing:

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

I am using AutoMapper v1.

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

My code is:

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

}

+1
source

Source: https://habr.com/ru/post/1731825/


All Articles