只有在属性中不为null时才自动处理多个属性

时间:2016-02-11 11:36:48

标签: c# automapper

我必须从多个属性返回类似string.Concat的CallerAddress属性,除非它们不为null。到目前为止,我已经尝试过这个,但是没有用。映射后,我的CallerAddress等于“Str.SomeStreetName”。我抬头查看了我的数据库,并且我对其他列有了价值。那么,我怎样才能使这个工作?

 Mapper.CreateMap<ClientRecordingsDao,ClientRecording>()
    .ForMember(x => x.CallerAddress,
                        b =>
                            b.MapFrom(
                                x => x.CallerStreet != String.Empty
                                    ? "Str." + x.CallerStreet 
                                    : String.Empty +
                                      x.CallerStreetNumber != String.Empty
                                        ? " Nr."
                                        : String.Empty + x.CallerStreetNumber +
                                          x.CallerBuilding != String.Empty
                                            ? " Bl."
                                            : String.Empty + x.CallerBuilding +
                                              x.CallerApartment != String.Empty
                                                ? " Ap."
                                                : String.Empty + x.CallerApartment))

1 个答案:

答案 0 :(得分:1)

它将+操作符应用于错误的位置。在()

中包含您的每个比较
 Mapper.CreateMap<ClientRecordingsDao,ClientRecording>()
     .ForMember(x => x.CallerAddress, b => b.MapFrom(
         x => (x.CallerStreet != String.Empty ? "Str." + x.CallerStreet : String.Empty) +
             (x.CallerStreetNumber != String.Empty ? " Nr." + x.CallerStreetNumber : String.Empty) +
             (x.CallerBuilding != String.Empty ? " Bl." + x.CallerBuilding : String.Empty) +
             (x.CallerApartment != String.Empty ? " Ap." + x.CallerApartment : String.Empty)));

您的代码映射到:

 Mapper.CreateMap<ClientRecordingsDao,ClientRecording>()
     .ForMember(x => x.CallerAddress, b => b.MapFrom(
         x => x.CallerStreet != String.Empty ? "Str." + x.CallerStreet :
         (String.Empty + x.CallerStreetNumber != String.Empty ? " Nr." + x.CallerStreetNumber :
         (String.Empty + x.CallerBuilding != String.Empty ? " Bl." + x.CallerBuilding : 
         (String.Empty + x.CallerApartment != String.Empty ? " Ap." +  x.CallerApartment : String.Empty)))));