C# 我告诉AutoMapper不要访问属性,为什么它要访问属性?
我已经设置了一个简单的测试用例;以下是我的类型:C# 我告诉AutoMapper不要访问属性,为什么它要访问属性?,c#,automapper,C#,Automapper,我已经设置了一个简单的测试用例;以下是我的类型: 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; } } pub
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";
});
});
到目前为止,似乎还不错,Parent
的映射在Name
为33时停止。但是,当我调试opt.Condition
lambda时,返回comp.Name!="33";
,我发现AutoMapper正在按以下顺序传递原始的FullCompanyInfo
对象:
Id: 44
Id: 33
Id: 22
Id: 11
因此,它正在访问所有4个对象,即使44
从未进入最终映射!这就好像Automapper正在完全探索对象图,然后在我的条件返回false时删除属性一样。为什么它不首先调用11
的lambda,依此类推,并且只加载FullCompanyInfo
子对象(如果它被告知映射该成员)
问题在于,在这样一个环境中,这些实体不仅仅是内存中的实体,而是需要花费时间和资源才能访问的实体,AutoMapper将访问它不需要的内容,而不是在条件告诉它不要映射引用的实体时停止。3个字母:Pre
真不敢相信我在这上面浪费了很多时间;我需要使用opt.premission(…)
。当您告诉它不要访问源成员时,它实际上会停止访问该成员。Yes:)请参阅。
{
"Id": 1,
"Name": "11",
"Parent": {
"Id": 2,
"Name": "22",
"Parent": {
"Id": 3,
"Name": "33",
"Parent": null
}
}
}
Id: 44
Id: 33
Id: 22
Id: 11