2017-07-13 9 views
5

Web APIコントローラメソッドでは、UpdatePlaceDTOPlaceMasterにマップする前に、マップでカバーされていないプロパティを読み込むためにデータベース呼び出しを行いますが、何らかの理由でAutoMapperによってそれらのプロパティがnullになります。AutoMapper 4.2はプロファイル内のプロパティを無視しない

var mappedPlaceMaster = _mapper.Map<PlaceMaster>(placeMasterDTO); 
// mappedPlaceMaster.EntityId is null 

私はIgnoreExistingMembersに多くのソリューションを試しましたが、どれも機能しません。

これは私が

public class PlaceMapperProfile : Profile 
    { 

     protected override void Configure() 
     { 
      // TO DO: This Mapping doesnt work. Need to ignore other properties 
      //CreateMap<UpdatePlaceDto, PlaceMaster>() 
      // .ForMember(d => d.Name, o => o.MapFrom(s => s.Name)) 
      // .ForMember(d => d.Description, o => o.MapFrom(s => s.Description)) 
      // .ForMember(d => d.ParentPlaceId, o => o.MapFrom(s => s.ParentPlaceId)) 
      // .ForMember(d => d.LeftBower, o => o.MapFrom(s => s.LeftBower)) 
      // .ForMember(d => d.RightBower, o => o.MapFrom(s => s.RightBower)).IgnoreAllNonExisting(); 
     } 
    } 

を持っているもの。これは、私が見てきた私のdepedenciesに

protected override void Load(ContainerBuilder builder) 
     { 
      //register all profile classes in the calling assembly 
      var profiles = 
       from t in typeof(Navigator.ItemManagement.Data.MappingProfiles.PlaceMapperProfile).Assembly.GetTypes() 
       where typeof(Profile).IsAssignableFrom(t) 
       select (Profile)Activator.CreateInstance(t); 

      builder.Register(context => new MapperConfiguration(cfg => 
      { 
       foreach (var profile in profiles) 
       { 
        cfg.AddProfile(profile); 
       } 


      })).AsSelf().SingleInstance(); 

      builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve)) 
       .As<IMapper>() 
       .SingleInstance(); 
     } 

をマッパーを注入するためにモジュールを使用しました延長

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) 
     { 
      foreach (var property in expression.TypeMap.GetUnmappedPropertyNames()) 
      { 
       expression.ForMember(property, opt => opt.Ignore()); 
      } 
      return expression; 
     } 

ですいくつかのスレッドでは、_mapper.Mapが実際に新しいオブジェクトを作成するので、既存のプロパティに「アドオン」を並べ替える方法相談する?

答えて

3

私は解決策を見つけました。それは私の目の前にあったが、私はそれを見なかった!

マップ機能のオーバーロードを使用するだけで、マップで使用可能なプロパティを割り当てずに、PlaceMasterの新しいインスタンスを作成する必要がありました。

mappedPlaceMaster = _mapper.Map(placeMasterDTO, placeMasterFromDatabase); 
+0

自分で解決策を見つけるためによくできました! –

関連する問題