AutoMapper and convert a datetime to string

我的梦境 提交于 2019-12-03 15:06:18

问题


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


回答1:


try this:

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



回答2:


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


来源:https://stackoverflow.com/questions/15007660/automapper-and-convert-a-datetime-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!