Automapper:基于源对象和ResolutionContext的条件映射
本文关键字:ResolutionContext 条件 映射 对象 于源 Automapper | 更新日期: 2023-09-27 18:15:48
我需要基于源对象和ResolutionContext做一个条件映射。下面是我的代码:
AutoMapper.Mapper.CreateMap<SourceType, DestinationType>()
.ForMember(dest => dest.Value, opt =>
{
opt.Condition(context=>
{
bool condition1 = (bool)context.Options.Items["Condition"];
bool condition2 = SomeFunction(context.SourceValue);
return !(condition1 && !condition2);
});
opt.MapFrom(src => src.Value);
});
不幸的是,这中断了,因为context.SourceValue
返回的是String
(而不是SourceType
)。我认为context.SourceValue
返回源对象,但这似乎不是情况。
是否有任何方法可以基于ResolutionContext和Source对象进行条件映射?
context.SourceValue
返回当前正在转换的成员,在本例中是SourceType.Value
(我猜是字符串)。
获取SourceType
对象,使用如下命令:
SourceType source_object = (SourceType)context.Parent.SourceValue;