简体   繁体   English

Automapper:基于Source对象和ResolutionContext的条件映射

[英]Automapper: Conditional mapping based on Source object and ResolutionContext

I need to make a conditional mapping based on both the source object and ResolutionContext. 我需要基于源对象和ResolutionContext进行条件映射。 Here is my code: 这是我的代码:

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);
        });

Unfortunately, this breaks because context.SourceValue is returning a String (not a SourceType ). 不幸的是,这会中断,因为context.SourceValue返回一个String (不是SourceType )。 I thought that context.SourceValue returned the source object, but this doesn't seem to be the case. 我认为context.SourceValue返回了源对象,但似乎并非如此。

Is there any way to do conditional mapping based on both the ResolutionContext and the Source object? 有没有办法根据ResolutionContext和Source对象进行条件映射?

context.SourceValue returns the member currently being converted, which in this case is SourceType.Value (which I guess is a string). context.SourceValue返回当前正在转换的成员,在本例中为SourceType.Value (我猜是一个字符串)。

To obtain the SourceType object, use the following: 要获取SourceType对象,请使用以下命令:

SourceType source_object = (SourceType)context.Parent.SourceValue;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM