Automapper: complex if else statement in ForMember

前端 未结 2 1319
执念已碎
执念已碎 2020-12-17 10:50

Assuming the Date is a nullable DateTime:

Mapper.CreateMap()               
             .ForMember(d         


        
相关标签:
2条回答
  • 2020-12-17 11:24

    Use ResolveUsing method:

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

    Here is more information: AutoMapper: MapFrom vs. ResolveUsing

    0 讨论(0)
  • 2020-12-17 11:27

    In recent versions of AutoMapper, ResolveUsing was removed. Instead, use a new overload of MapFrom:

    void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction);
    

    Just adding another lambda/function parameter will dispatch to this new overload:

            CreateMap<TSource, TDest>()
                    .ForMember(dest => dest.SomeDestProp, opt => opt.MapFrom((src, dest) =>
                    {
                        TSomeDestProp destinationValue;
    
                        // mapping logic goes here
    
                        return destinationValue;
                    }));
    
    0 讨论(0)
提交回复
热议问题