Skip to content

Condition when mapping from Nullable<T> to T #2999

Description

@MarkSFrancis

When using a condition to check the value of a member of type Nullable before mapping to a destination member with a type T, the value is converted to T before Condition is checked, and so checking for null will not work correctly.

Source/destination types

class Source
{
    public int? Value { get; set; }
}

class Destination
{
    public int Value { get; set; }
}

Mapping configuration

cfg.CreateMap<Source, Destination>().ForAllMembers(o => o.Condition((source, destination, sourceProperty, destinationProperty) =>
{
    sourceProperty.ShouldBeNull(); // Fails as it's already converted int? to int before it reaches this, and so the value is 0
    
    // Always true
    return sourceProperty != null;
}));

Version: x.y.z

8.1.0

Expected behavior

Type of sourceProperty should be Nullable<Int32>

Actual behavior

Type of sourceProperty is Int32

Steps to reproduce

public class when_mapping_from_nullable_clr_member : AutoMapperSpecBase
{
    Source _source = new Source { Value = null };
    Destination _destination = new Destination { Value = 7 };

    class Source
    {
        public int? Value { get; set; }
    }

    class Destination
    {
        public int Value { get; set; }
    }

    protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<Source, Destination>().ForAllMembers(o => o.Condition((source, destination, sourceProperty, destinationProperty) =>
        {
            sourceProperty.ShouldBeNull();

            // Always true
            return sourceProperty != null;
        }));
    });

    protected override void Because_of()
    {
        Mapper.Map(_source, _destination);
    }
}

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions