2017-12-21 18 views
0

一部のSharePointライブラリに1つの問題があります。私の 'Model'オブジェクトを 'ListItem'オブジェクトにマップしたいと思います。残念ながら、 'ListItem'オブジェクトにはコンストラクタがなく、SharePointライブラリ内にある関数で初期化する必要があります。マッピングされたオブジェクトのインスタンスを(マッピングの前に)与えることは可能ですか?作成したオブジェクトインスタンスをマッパーに渡す

public void AddToList(Model model) 
    { 
     // 'new ListItem()' is fobbiden. 'CreateListItemInstance()' 
     // creates 'instance' using client context, list name which aren't 
     // inside 'model' object. 
     ListItem instance = this.CreateListItemInstance(); 

     // (Model -> ListItem) It throws exception, because automapper 
     // try to create instance of ListItem. 
     ListItem parsedItem = Mapper.Map<ListItem>(model); 

     // I would like to have something like below: 
     // Mapper.Map<ListItem>(model).UseInstance(instance); 


     this.SharePointListItemRepository.Insert(parsedItem); 
     this.SharePointListItemRepository.Save(); 
    } 

アップデート(2017年12月22日)

Iマッパーするインスタンスを渡すResolutionContextを使用し、私はインスタンスにコンストラクタを交換するConstructUsingメソッドでこのインスタンスを使用します。

  CreateMap<Model, ListItem>() 
      //Using 'ConstructUsing' method to use instance of Model 
      //(from resolutionContext) as constructor. 
      .ConstructUsing((source, resolutionContext) => 
      (resolutionContext.Items["instance"] as ListItem)) 
      //Mappings... 
      .AfterMap((source, destination) => 
      { 
       destination["Title"] = source.Title; 
      }); 

答えて

0

チェックアウトthis article:我々は唯一のAutoMapperにカスタムリゾルバの種類を供給するので、マッピング・エンジンが作成するためにリフレクションを使用します

マッププロファイル内

 ListItem instance = this.CreateListItemInstance(); 

     ListItem parsed = mapper.Map<ListItem>(model, opts => 
     opts.Items["instance"] = instance); //passing instance to ResolutioContext 

     this.SharePointListItemRepository.Insert(parsed); 
     this.Save(); 

値リゾルバのインスタンス。

我々はAutoMapperは、インスタンスを作成するためにリフレクションを使用したくない場合は、我々はそれを直接供給することができます:

Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>() 
    .ForMember(dest => dest.Total, 
     opt => opt.ResolveUsing(new CustomResolver()) 
    ); 

opt.ResolveUsing(new CustomResolver()) 

の代わりにがあるかもしれません。

opt.ResolveUsing(CreateListItemInstance()) 
関連する問題