Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper and convert a datetime to string

Tags:

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

like image 535
jaffa Avatar asked Feb 21 '13 16:02

jaffa


2 Answers

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();                                     })); 
like image 150
Mrchief Avatar answered Oct 05 '22 02:10

Mrchief


try this:

Mapper.CreateMap<I_NEWS, NewsModel>().ForMember(x => x.DateCreated,   opt => opt.MapFrom(src => ((DateTime)src.DateCreated).ToShortDateString())); 
like image 35
Ricardo Rodrigues Avatar answered Oct 05 '22 02:10

Ricardo Rodrigues