本文介绍了如果在复杂的其他ForMember声明:Automapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设日期为空日期时间:

Assuming the Date is nullable DateTime:

Mapper.CreateMap<SomeViewModels, SomeDTO>()
             .ForMember(dest => dest.Date,
                        opt => opt.MapFrom(src =>
                        {
                            DateTime? finalDate = null;
                            if (src.HasDate == "N")
                            {
                                // so it should be null
                            }
                            else
                            {
                                endResult = DateTime.Parse(src.Date.ToString());

                            }
                            return finalDate;

                        }));



我得到的错误是:错误30与语句体lambda表达式不能转换为表达式树

The error I got was: "Error 30 A lambda expression with a statement body cannot be converted to an expression tree"

当然,我完全awared我可以简化查询,如:

Of course I'm fully awared that I can simplify the query such as:

Mapper.CreateMap<SomeViewModels, SomeDTO>()
             .ForMember(dest => dest.Date,
                        opt => opt.MapFrom(src => src.HasDate == "N" ? null : DateTime.Parse(src.Date.ToString())));



但是,如果我坚持保留第一例的结构,因为我如果else语句更为复杂的是什么第二例不能够满足,或者至少不是很可读?

But what if I insist to retain the structure of the first example because I have more complicated if else statements that the second example will not able to cater or at least not very readable?

推荐答案

使用的方式:

Mapper.CreateMap<SomeViewModels, SomeDTO>()
         .ForMember(dest => dest.Date, o => o.ResolveUsing(Converter));

private static object Converter(SomeViewModels value)
{
    DateTime? finalDate = null;
    if (value.Date.HasDate == "N")
    {
        // so it should be null
    }
    else
    {
        finalDate = DateTime.Parse(value.Date.ToString());
    }
    return finalDate;
}

下面是详细信息:的

这篇关于如果在复杂的其他ForMember声明:Automapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 18:32