Skip to content

Conditional mapping with nested adapters fails for one type but works for another identical pattern #926

Open

Description

@vamanpnayak

Conditional mapping with nested adapters fails for one type but works for another identical pattern

Summary

When using conditional mapping (3-parameter .Map() overload) with OneOf types, Mapster successfully applies nested adapters for EncryptedCard but fails to apply them for PlaintextCard, even though both use the exact same mapping pattern. The PlaintextCard property is set to null instead of being mapped through the registered adapter.

Environment

  • Mapster Version: 7.4.0
  • Mapster.Core Version: 1.2.1
  • MapsterMapper Version: 1.0.2
  • .NET Version: .NET 9.0
  • Project Type: ASP.NET Core Web API with gRPC

Minimal Reproduction

Source Types

// OneOf discriminated union
[GenerateOneOf]
public partial class CardOf : OneOfBase<CardWithPlainTextPan, CardWithEncryptedPan>;

public record CardWithPlainTextPan(string Pan, string ExpiryYear, string ExpiryMonth);

public record CardWithEncryptedPan(
    string EncryptedCardData,
    string ExpiryYear,
    string ExpiryMonth);

public record AccountUpdaterInquiryResponse(InquiryStatus Status, Maybe<CardOf> Card);

Destination Types (Protobuf Generated)

// From protobuf - simplified
public sealed partial class InquiryResponse
{
    public Processing.Card.V2.Card PlaintextCard { get; set; }
    public Processing.Card.V2.EncryptedCard EncryptedCard { get; set; }
    public InquiryStatus Status { get; set; }
    public enum AccountOneofCase { None, PlaintextCard, EncryptedCard }
}

public sealed partial class Card
{
    public string Pan { get; set; }
    public string ExpiryYear { get; set; }
    public string ExpiryMonth { get; set; }
    public string Cvc { get; set; } // Optional field
}

public sealed partial class EncryptedCard
{
    public string JweCompactEncryptedData { get; set; }
    public string ExpiryYear { get; set; }
    public string ExpiryMonth { get; set; }
    public EncryptedCardContentType EncryptedDataContentType { get; set; }
}

Mapper Configuration

public class InquiryResponseMapper : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        // Nested adapter for PlaintextCard
        config.NewConfig<CardWithPlainTextPan, Processing.Card.V2.Card>()
            .Map(d => d.Pan, s => s.Pan)
            .Map(d => d.ExpiryMonth, s => s.ExpiryMonth)
            .Map(d => d.ExpiryYear, s => s.ExpiryYear)
            .Ignore(d => d.Cvc);

        // Nested adapter for EncryptedCard
        config.NewConfig<CardWithEncryptedPan, Processing.Card.V2.EncryptedCard>()
            .Map(d => d.JweCompactEncryptedData, s => s.EncryptedCardData)
            .Map(d => d.EncryptedDataContentType, 
                s => Processing.Card.V2.EncryptedCardContentType.JsonCardNumberWithOptCvvCamelCase)
            .Map(d => d.ExpiryYear, s => s.ExpiryYear)
            .Map(d => d.ExpiryMonth, s => s.ExpiryMonth);

        // Main mapping with conditional logic
        config.NewConfig<AccountUpdaterInquiryResponse, InquiryResponse>()
            .Map(d => d.PlaintextCard, s => s.Card.Value.AsT0, s => s.Card.HasValue && s.Card.Value.IsT0)
            .Map(d => d.EncryptedCard, s => s.Card.Value.AsT1, s => s.Card.HasValue && s.Card.Value.IsT1)
            .Map(d => d.Status, s => ConvertInquiryStatus(s.Status));
    }
}

Test Configuration

var config = new TypeAdapterConfig();
config.Default.RequireDestinationMemberSource(value: true);
new InquiryResponseMapper().Register(config);
config.Compile();
var mapper = new Mapper(config);

Expected Behavior

Both PlaintextCard and EncryptedCard should be mapped through their respective nested adapters:

  • When Card.Value.IsT0 is true, PlaintextCard should be populated via CardWithPlainTextPan -> Processing.Card.V2.Card adapter
  • When Card.Value.IsT1 is true, EncryptedCard should be populated via CardWithEncryptedPan -> Processing.Card.V2.EncryptedCard adapter

Actual Behavior

  • ✅ EncryptedCard works correctly - nested adapter is applied, all fields mapped
  • ❌ PlaintextCard is null - nested adapter is NOT applied, even though the condition evaluates to true

Test Results

Passed:  18 tests for EncryptedCard mapping
Failed:   8 tests for PlaintextCard mapping (NullReferenceException on line accessing PlaintextCard.Pan)

What We've Tried

  1. Reordering configurations - Registering PlaintextCard adapter before EncryptedCard
  2. Different mapping approaches:
    • Ternary operator: .Map(d => d.PlaintextCard, s => s.Card.HasValue && s.Card.Value.IsT0 ? s.Card.Value.AsT0 : null)
    • AfterMapping callbacks
    • Manual adapter invocation functions
  3. Property mapping variations:
    • Changed property order to match constructor
    • Explicit mapping of Cvc to empty string instead of Ignore
  4. Type disambiguation - Added using Card = Processing.Card.V2.Card; alias
  5. ForType declarations - Explicitly declaring both adapters with config.ForType<>()

None of these approaches resolved the issue, while EncryptedCard continues to work perfectly with the exact same pattern.

Key Observations

  1. The problem is asymmetric - identical mapping patterns behave differently
  2. The destination type name Card is very generic, while EncryptedCard is more specific
  3. Source types use OneOf discriminated unions from the OneOf NuGet package
  4. Destination types are protobuf-generated with oneof fields
  5. The nested adapter IS registered and CAN be used directly, but isn't invoked through conditional mapping
  6. RequireDestinationMemberSource(true) is satisfied (no compilation errors about unmapped members)

Workaround Needed

Is there a recommended pattern for mapping through OneOf types with nested adapters that ensures consistent behavior? Or is this a bug that needs fixing?

Additional Context

This appears to be related to how Mapster resolves and applies nested adapters when the source value comes from a conditional expression involving discriminated union types. The fact that one type works and another doesn't suggests there may be type resolution or caching issues specific to certain type names or structures.

Activity

  1. DocSvartz commented on Apr 22, 2026

    @DocSvartz
    Contributor

    Hi @vamanpnayak you try it in v10+ ?

  2. DocSvartz commented on Apr 22, 2026

    @DocSvartz
    Contributor

    I Check it work in 7.4.0 . 🤔

    Are you absolutely sure that Protobuf generates a
    public sealed partial class Card

    in the Processing.Card.V2 namespace.
    and that the InquiryResponse actually contains a Property Card reference from that namespace?

    Perhaps CardWithPlainTextPan is from a different namespase, not the one you've configured the mapping for.

    using Functional.Maybe;
    using Mapster;
    using MapsterMapper;
    using OneOf;
    using Shouldly;
    
    namespace TestREgressionMapster
    {
        [TestClass]
        public class CardTests
        {
            [TestMethod]
            public void CardWork()
            {
                var config = new TypeAdapterConfig();
    
                config.NewConfig<CardWithPlainTextPan, Card>()
                .Map(d => d.Pan, s => s.Pan)
                .Map(d => d.ExpiryMonth, s => s.ExpiryMonth)
                .Map(d => d.ExpiryYear, s => s.ExpiryYear)
                .Ignore(d => d.Cvc);
    
                // Nested adapter for EncryptedCard
                config.NewConfig<CardWithEncryptedPan, EncryptedCard>()
                    .Map(d => d.JweCompactEncryptedData, s => s.EncryptedCardData)
                    .Map(d => d.ExpiryYear, s => s.ExpiryYear)
                    .Map(d => d.ExpiryMonth, s => s.ExpiryMonth);
    
                // Main mapping with conditional logic
                config.NewConfig<AccountUpdaterInquiryResponse, InquiryResponse>()
                    .Map(d => d.PlaintextCard, s => s.Card.Value.AsT0, s => s.Card.HasValue && s.Card.Value.IsT0)
                    .Map(d => d.EncryptedCard, s => s.Card.Value.AsT1, s => s.Card.HasValue && s.Card.Value.IsT1)
                    ;
    
                config.Compile();
                var mapper = new Mapper(config);
               
    
                var sourceEncrypt = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "111" }, ((CardOf)new CardWithEncryptedPan("www", "www", "www")).ToMaybe());
                var sourceText = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "111" }, ((CardOf)new CardWithPlainTextPan("www", "www", "www")).ToMaybe());
    
                var resultEncrypt = mapper.Map<InquiryResponse>(sourceEncrypt);
                var resultText = mapper.Map<InquiryResponse>(sourceText);
    
                resultEncrypt.EncryptedCard.ShouldNotBeNull();
                resultEncrypt.EncryptedCard.ExpiryMonth.ShouldNotBeNull();
    
                resultText.PlaintextCard.ShouldNotBeNull();
                resultText.PlaintextCard.Pan.ShouldNotBeNullOrEmpty();
            }
    
    
            
    
        }
    
    
        [GenerateOneOf]
        public partial class CardOf : OneOfBase<CardWithPlainTextPan, CardWithEncryptedPan>;
    
        public record CardWithPlainTextPan(string Pan, string ExpiryYear, string ExpiryMonth);
    
        public record CardWithEncryptedPan(
            string EncryptedCardData,
            string ExpiryYear,
            string ExpiryMonth);
    
        public record AccountUpdaterInquiryResponse(InquiryStatus Status, Maybe<CardOf> Card);
    
        public class InquiryStatus
        {
            public string Text { get; set; }
        }
    
        public sealed partial class InquiryResponse
        {
            public Card PlaintextCard { get; set; }
            public EncryptedCard EncryptedCard { get; set; }
            //public InquiryStatus Status { get; set; }
            public enum AccountOneofCase { None, PlaintextCard, EncryptedCard }
        }
    
        public sealed partial class Card
        {
            public string Pan { get; set; }
            public string ExpiryYear { get; set; }
            public string ExpiryMonth { get; set; }
            public string Cvc { get; set; } // Optional field
        }
    
        public sealed partial class EncryptedCard
        {
            public string JweCompactEncryptedData { get; set; }
            public string ExpiryYear { get; set; }
            public string ExpiryMonth { get; set; }
            //public EncryptedCardContentType EncryptedDataContentType { get; set; }
        }
    
    
    
    }
    
  3. DocSvartz commented on Apr 22, 2026

    @DocSvartz
    Contributor

    namespace test - fail. config create to CardWithPlainTextPan from another namespace

    using Functional.Maybe;
    using Mapster;
    using MapsterMapper;
    using OneOf;
    using Shouldly;
    
    namespace TestREgressionMapster
    {
        [TestClass]
        public class CardTests
        {
            [TestMethod]
            public void CardWork()
            {
                var config = new TypeAdapterConfig();
    
                config.Default.IgnoreNonMapped(true); // simulating different names. Otherwise, the settings below are not needed. Since automatic matching will work
    
                config.NewConfig<v1.CardWithPlainTextPan, Card>()
                .Map(d => d.Pan, s => s.Pan)
                .Map(d => d.ExpiryMonth, s => s.ExpiryMonth)
                .Map(d => d.ExpiryYear, s => s.ExpiryYear)
                .Ignore(d => d.Cvc);
    
                // Nested adapter for EncryptedCard
                config.NewConfig<CardWithEncryptedPan, EncryptedCard>()
                    .Map(d => d.JweCompactEncryptedData, s => s.EncryptedCardData)
                    .Map(d => d.ExpiryYear, s => s.ExpiryYear)
                    .Map(d => d.ExpiryMonth, s => s.ExpiryMonth);
    
                // Main mapping with conditional logic
                config.NewConfig<AccountUpdaterInquiryResponse, InquiryResponse>()
                    .Map(d => d.PlaintextCard, s => s.Card.Value.AsT0, s => s.Card.HasValue && s.Card.Value.IsT0)
                    .Map(d => d.EncryptedCard, s => s.Card.Value.AsT1, s => s.Card.HasValue && s.Card.Value.IsT1)
                    ;
    
                config.Compile();
                var mapper = new Mapper(config);
    
                v2.CardWithPlainTextPan cardata = new v2.CardWithPlainTextPan("www", "www", "www");
    
    
                var sourceEncrypt = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "111" }, ((CardOf)new CardWithEncryptedPan("www", "www", "www")).ToMaybe());
                var sourceText = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "111" }, ((CardOf)cardata).ToMaybe());
    
                var resultEncrypt = mapper.Map<InquiryResponse>(sourceEncrypt);
                var resultText = mapper.Map<InquiryResponse>(sourceText);
    
                resultEncrypt.EncryptedCard.ShouldNotBeNull();
                resultEncrypt.EncryptedCard.ExpiryMonth.ShouldNotBeNull();
    
                resultText.PlaintextCard.ShouldNotBeNull();
                resultText.PlaintextCard.Pan.ShouldNotBeNullOrEmpty();
            }
    
    
            
    
        }
    
    
        [GenerateOneOf]
        public partial class CardOf : OneOfBase<v2.CardWithPlainTextPan, CardWithEncryptedPan>;
    
        
    
        public record CardWithEncryptedPan(
            string EncryptedCardData,
            string ExpiryYear,
            string ExpiryMonth);
    
        public record AccountUpdaterInquiryResponse(InquiryStatus Status, Maybe<CardOf> Card);
    
        public class InquiryStatus
        {
            public string Text { get; set; }
        }
    
        public sealed partial class InquiryResponse
        {
            public Card PlaintextCard { get; set; }
            public EncryptedCard EncryptedCard { get; set; }
            //public InquiryStatus Status { get; set; }
            public enum AccountOneofCase { None, PlaintextCard, EncryptedCard }
        }
    
        public sealed partial class Card
        {
            public string Pan { get; set; }
            public string ExpiryYear { get; set; }
            public string ExpiryMonth { get; set; }
            public string Cvc { get; set; } // Optional field
        }
    
        public sealed partial class EncryptedCard
        {
            public string JweCompactEncryptedData { get; set; }
            public string ExpiryYear { get; set; }
            public string ExpiryMonth { get; set; }
            //public EncryptedCardContentType EncryptedDataContentType { get; set; }
        }
    
    
    
    }
    
    namespace v1
    {
        public record CardWithPlainTextPan(string Pan, string ExpiryYear, string ExpiryMonth);
    }
    
    namespace v2
    {
        public record CardWithPlainTextPan(string Pan, string ExpiryYear, string ExpiryMonth);
    }
    
  4. vamanpnayak commented on Apr 22, 2026

    @vamanpnayak
    Author

    Confirmation

    Yes, The C# Protocol Buffer compiler (protoc) generates a public sealed partial class for messages defined in a .proto file :

    • public sealed partial class Card in the Processing.Card.V2 namespace
    • InquiryResponse contains property: public global::Processing.Card.V2.Card PlaintextCard

    Verified with namespece. All good there.

    The Mystery

    Both PlaintextCard and EncryptedCard use identical mapping patterns:

    .Map(d => d.PlaintextCard, s => s.Card.Value.AsT0, s => s.Card.HasValue && s.Card.Value.IsT0)
    .Map(d => d.EncryptedCard, s => s.Card.Value.AsT1, s => s.Card.HasValue && s.Card.Value.IsT1)
    
    I will try other options around by changing the logic to see if something else is contribution on this issue.
  5. DocSvartz commented on Apr 22, 2026

    @DocSvartz
    Contributor

    you using Map or MapToTarget ?

    • mapper.Map(sourceText) - Map
    • mapper.Map(sourceText, destination) - MapToTarget

    You can provide DebugView of Expression?

     mapper.From(sourceText).CreateMapToTargetExpression<InquiryResponse>(); 
    or 
     mapper.From(sourceText).CreateMapExpression<InquiryResponse>();
    
  6. DocSvartz commented on Apr 22, 2026

    @DocSvartz
    Contributor

    @vamanpnayak Perhaps you need an update without overwriting?
    Then the configuration should look something like this.

      config.NewConfig<AccountUpdaterInquiryResponse, InquiryResponse>()
          .Map(d => d.PlaintextCard, s => s.Card.Value.Value)
          .Map(d => d.EncryptedCard, s => s.Card.Value.Value)
          .IgnoreIf((s, dest) => !s.Card.HasValue || s.Card.Value.IsT1, dest => dest.PlaintextCard)
          .IgnoreIf((s, dest) => !s.Card.HasValue || s.Card.Value.IsT0, dest => dest.EncryptedCard);
    
    var patchsourceEncrypt = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "222" }, ((CardOf)new CardWithEncryptedPan("yyy", "yyy", "yyy")).ToMaybe());
    var patchsourceText = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "333" }, ((CardOf)new CardWithPlainTextPan("yyy", "yyy", "yyy")).ToMaybe());
     var nullpatch = new AccountUpdaterInquiryResponse(new InquiryStatus { Text = "222" }, Maybe<CardOf>.Nothing);
    
    
    var updateEncryptToText = mapper.Map(patchsourceEncrypt, resultText);
    var updateTextToEncrypt = mapper.Map(patchsourceText, resultEncrypt);
    var updateNullpatch = mapper.Map(nullpatch, resultEncrypt); // not update
    
    
  7. DocSvartz commented on Apr 23, 2026

    @DocSvartz
    Contributor

    Is there a recommended pattern for mapping through OneOf types with nested adapters that ensures consistent behavior? Or is this a bug that needs fixing?

    Apparently, you misunderstood what the condition in conditional mapping does.
    The condition in conditional mapping is needed to provide an alternative source.
    If all conditions for providing alternative sources fail, the default value for type or unconditional source will be provided .
    This is specified in the wiki.

    If you don't want to pass a value from a source depending on a specific conditional , then you need to use IgnoreIF.

    Ternary operator: .Map(d => d.PlaintextCard, s => s.Card.HasValue && s.Card.Value.IsT0 ? s.Card.Value.AsT0 : null)
    AfterMapping callbacks

    I don't recommend this.
    The source must be an unconditional path to a real source or anonymous lambda functions .

  8. DocSvartz commented on Apr 23, 2026

    @DocSvartz
    Contributor

    Property mapping variations:
    Changed property order to match constructor
    Explicit mapping of Cvc to empty string instead of Ignore

    @vamanpnayak Destination type has constructors ?
    Your examples don't have it.
    And do all fields really have public setters?

    If this is the case, it could also be related to record detection.

  9. vamanpnayak commented on Apr 27, 2026

    @vamanpnayak
    Author

    Hi, Sorry for delay in the response. Your tip helped to fix it. IgnoreIf + map helped to get the success.

    Map with Conditional like below didnt work ❌. (It was not meant for this use case)

    TypeAdapterConfig<Source, Destination>.NewConfig()
    // Property 1: Only map Name if union is T0 AND name starts with 'A'
    .Map(dest => dest.Name,
    src => src.MyUnion.AsT0.Name,
    src => src.MyUnion.IsT0 && src.MyUnion.AsT0.Name.StartsWith("A"))

    Map with PreCondition option like below didnt work ❌

    TypeAdapterConfig<Source, Destination>.NewConfig()
    .ForMember(
    dest => dest.Name,
    opt => {
    opt.PreCondition(src.MyUnion.AsT0.Name.StartsWith("A"));
    opt.MapFrom(src => src.MyUnion.AsT0.Name
    }

    IgnoreIf + Map worked ✅

    TypeAdapterConfig<Source, Destination>.NewConfig()
    // Handle Name
    .IgnoreIf((src, dest) => !src.MyUnion.IsT0 || src.MyUnion.AsT0.SomeValue == null,
    dest => dest.Name)
    .Map(dest => dest.Name, src => src.MyUnion.AsT0.Name)

    If you feel, This the expected behaviour then please proceed to close the case. :)
    You were really helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions