AutoMapper and convert a datetime to string

前端 未结 3 1706
一向
一向 2021-02-07 02:12

I can\'t get my head round the following issue. I have a feeling it is a limitation of LINQ and expression trees, but not sure how to accept the lambda body. Can I achieve this

相关标签:
3条回答
  • 2021-02-07 02:48

    In order to use lambda bodies, use .ResolveUsing instead of .MapFrom.

    As per the author:

    MapFrom has some extra stuff that needs expression trees (like null checking etc).

    So your statement would look like this:

     Mapper.CreateMap<I_NEWS, NewsModel>()                  
                  .ForMember(x => x.DateCreated, opt => opt.ResolveUsing(src => {
                      var dt = (DateTime)src.DateCreated;
                      return dt.ToShortDateString();                      
                  }));
    
    0 讨论(0)
  • 2021-02-07 02:48

    If Nullable is destination then:

    Mapper.CreateMap() .ForMember( dest => dest.StartDate, opt => opt.MapFrom( src => string.IsNullOrEmpty(src.StartDate) ? new DateTime?() : DateTime.ParseExact(src.StartDate, DATEFORMAT, CultureInfo.InvariantCulture) ) )
    0 讨论(0)
  • 2021-02-07 03:02

    try this:

    Mapper.CreateMap<I_NEWS, NewsModel>().ForMember(x => x.DateCreated,
      opt => opt.MapFrom(src => ((DateTime)src.DateCreated).ToShortDateString()));
    
    0 讨论(0)
提交回复
热议问题