仅当它们在 属性 中不为空时才自动映射多个属性

Automapper multiple porperties only if they are not null in on property

我必须 return CallerAddress 属性 就像来自多个属性的 string.Concat 一样,除非它们不为空。到目前为止,我已经尝试过了,但没有用。映射后我的 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))

它将 + 运算符应用到错误的地方。将您的每个比较包装在 ():

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