代码之家  ›  专栏  ›  技术社区  ›  CRice

AutoMapper:在站点范围内对给定类型使用IValueFormatter

  •  1
  • CRice  · 技术社区  · 16 年前

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

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

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

    我正在绘制地图 约会时间?成员。出生日期 到 字符串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();
        }
    }
    
    3 回复  |  直到 16 年前
        1
  •  5
  •   krhayde    16 年前

    我也遇到了同样的问题,找到了解决办法。尝试更改:

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

    至

    Mapper.ForSourceType<DateTime>().AddFormatter<StandardDateFormatter>();
    
        2
  •  2
  •   Arkady Spiridonov    13 年前

    仅供参考-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();
        }
    }
    
        3
  •  1
  •   ozczecho    16 年前

    那里有一个抽象类,它完成了大部分繁重的工作,称为ValueFormatter。

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

    然后在我的个人资料课上:

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