开发者

Mapping from different properties based on discriminator value using AutoMapper

开发者 https://www.devze.com 2022-12-23 09:29 出处:网络
I have one very general object that I want to map to a destination type using AutomMapper, but I want to map it to different types depending on the value of a property in the source type. For example,

I have one very general object that I want to map to a destination type using AutomMapper, but I want to map it to different types depending on the value of a property in the source type. For example, let's say I have:

public class Source
{
    public string Discriminator { get; }
    public string ValueA { get; }
    public string ValueB { get; }
}

public class Target
{
    public string Value { get; set; }
}

And I want to map Source.ValueA to Target.Value if Source.Discriminator == "A" and Source.ValueB to Target.Value if Source.Discriminator == "B".

开发者_如何学PythonIs this possible using AutoMapper?


You can do something like this:

Mapper.Map<Spurce, Target>().ForMember(x => x.Value, x => x.MapFrom(y => {
    if(y.Discriminator == "A")
        return y.ValueA;
    return y.ValueB;
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消