Automapper:基于Source对象和ResolutionContext的条件映射
Automapper: Conditional mapping based on Source object and ResolutionContext
我需要根据源对象和 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
returns 当前正在转换的成员,在本例中是 SourceType.Value
(我猜是一个字符串)。
要获取 SourceType
对象,请使用以下命令:
SourceType source_object = (SourceType)context.Parent.SourceValue;
我需要根据源对象和 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
returns 当前正在转换的成员,在本例中是 SourceType.Value
(我猜是一个字符串)。
要获取 SourceType
对象,请使用以下命令:
SourceType source_object = (SourceType)context.Parent.SourceValue;