Search code examples
c#.netlinqautomapper

AutoMapper and convert a datetime to string


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 WITHOUT creating a custom converter?

 Mapper.CreateMap<I_NEWS, NewsModel>()                  
              .ForMember(x => x.DateCreated, opt => opt.MapFrom(src => {
                  var dt = (DateTime)src.DateCreated;
                  return dt.ToShortDateString();                      
              }));

I'm getting this error: A lambda expression with a statement body cannot be converted to an expression tree


Solution

  • try this:

    Mapper.CreateMap<I_NEWS, NewsModel>().ForMember(x => x.DateCreated,
      opt => opt.MapFrom(src => ((DateTime)src.DateCreated).ToShortDateString()));