Automapper:ForMember 中的复杂 if else 语句 [英] Automapper: complex if else statement in ForMember

查看:132
本文介绍了Automapper:ForMember 中的复杂 if else 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设 Date 是可空的 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 表达式到表达式树.

Error 30 A lambda expression with a statement body cannot be converted to an expression tree.

当然,我完全知道我可以简化查询,例如:

Of course I'm fully aware 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())));
    

但是如果我坚持保留第一个例子的结构怎么办,因为我有更复杂的 if 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 for, or at least will not be very readable?

推荐答案

使用 ResolveUsing 方法:

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

以下是更多信息:AutoMapper:MapFrom 与 ResolveUsing

这篇关于Automapper:ForMember 中的复杂 if else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆