![](/img/trans.png)
[英]Auto mapper issue with Object reference not set to an instance of an object
[英]Passing created object instance to mapper
我對某些SharePoint庫有一個問題。 我想將我的“模型”對象映射到“ 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();
}
更新(12/22/2017)
我使用ResolutionContext將實例傳遞給映射器,並在ConstructUsing方法中使用此實例將構造函數替換為實例。
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();
內部地圖資料:
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;
});
看看這篇文章 :
因為我們只向AutoMapper提供了自定義解析器的類型,所以映射引擎將使用反射來創建值解析器的實例。
如果我們不希望AutoMapper使用反射創建實例,則可以直接提供它:
Mapper.Initialize(cfg => cfg.CreateMap<Source, Destination>() .ForMember(dest => dest.Total, opt => opt.ResolveUsing(new CustomResolver()) );
代替
opt.ResolveUsing(new CustomResolver())
可能有:
opt.ResolveUsing(CreateListItemInstance())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.