![](/img/trans.png)
[英]Can you tell AutoMapper to globally ignore missing properties when mapping?
[英]Why is AutoMapper accessing properties when I tell it not to?
我設置了一個簡單的測試用例; 這是我的類型:
public class FullCompanyInfo {
public int Id { get; set; }
public string Name { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }
public FullCompanyInfo Parent { get; set; }
}
public class CompanyInChainDTO
{
public int Id { get; set; }
public string Name { get; set; }
public CompanyInChainDTO Parent { get; set; }
}
這是我的映射配置:
cfg.CreateMap<FullCompanyInfo, CompanyInChainDTO>()
.ForMember(dto => dto.Parent, opt =>
{
// Stop recursive parent mapping when name is 33
opt.Condition(comp => {
return comp.Name != "33";
});
});
現在我將原始對象圖設置為映射,映射並顯示JSON結果:
FullCompanyInfo comp = new FullCompanyInfo
{ Id = 1, Name = "11", Foo = "Foo1", Bar = "Bar1", Parent = new FullCompanyInfo
{ Id = 2, Name = "22", Foo = "Foo2", Bar = "Bar2", Parent = new FullCompanyInfo
{ Id = 3, Name = "33", Foo = "Foo3", Bar = "Bar3", Parent = new FullCompanyInfo {
Id = 4, Name = "44", Foo = "Foo4", Bar = "Bar4", Parent = null }
}
}
};
CompanyInChainDTO compChain = _mapper.Map<CompanyInChainDTO>(comp);
var jsonResult = JsonConvert.SerializeObject(compChain);
結果是:
{
"Id": 1,
"Name": "11",
"Parent": {
"Id": 2,
"Name": "22",
"Parent": {
"Id": 3,
"Name": "33",
"Parent": null
}
}
}
到目前為止看起來很好,當Name
為33時, Parent
的映射停止了。但是,當我在return comp.Name != "33";
調試opt.Condition
lambda時return comp.Name != "33";
,我發現AutoMapper按以下順序傳入原始的FullCompanyInfo
對象:
Id: 44
Id: 33
Id: 22
Id: 11
所以它正在訪問所有4個對象,即使44
從未進入最終映射! 就好像Automapper正在完全探索對象圖,然后在Condition
返回false時刪除屬性。 為什么它不首先調用lambda為11
,依此類推,只有在被告知映射該成員時才加載FullCompanyInfo
子對象?
麻煩的是,在這些不僅僅是內存實體的環境中,而是需要時間和資源來訪問的實體,AutoMapper將訪問它不需要的東西,而不僅僅是當Condition
告訴它不要停止時映射引用的實體。
3個字母: Pre
。
不敢相信我浪費了很多時間在這上面; 我需要使用opt.PreCondition(...)
代替。 當你告訴它不要時,它實際上停止訪問源成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.