Skip to content

Nullable source property to value type #2918

Description

@jhenderson2099

Documentation Request

Please document how the (default) value for a destination property that doesn't exist in the source object is determined.

This is being logged at the request of @jbogard . Please refer to https://groups.google.com/forum/#!topic/automapper-users/UX-liQGboMY

(Basically, "This is how it works if you works if the mapping is/isn't explicit/implicit and what you get as a default)

Suggestion is document it as part of Inline Mapping
[https://automapper.readthedocs.io/en/latest/Inline-Mapping.html]
(https://automapper.readthedocs.io/en/latest/Inline-Mapping.html)

Example Source/destination types

    public class Source
    {
        public double? Balance { get; set; }

    }


    public class Destination
    {
        public double Balance { get; set; }   // Not nullable!
    }

Mapping configuration

CreateMap<Source, Destination>(); // Implicit property-to-property mapping

or

// Explicit property-to-property mapping
CreateMap<Source, Destination>()
    .ForMember(dest => dest.Balance, opt => opt.MapFrom(src => src.Balance))

Version: x.y.z

7.0.0

Questions to be answered

  • If Source.Balance == null, then what will be the value of Destination.Balance?
  • Does AutoMapper convert the null to zero, or does the instance of Destination simply get initialized to 0 and no mapping occurs?
  • What would happen in this scenario if the two property names did not match and there was no explicit mapping? What would be the value of Destination.Balance?

I think it works like this: if you have a nullable source property and the value of the source property is nulland a non-nullable destination property (based upon my testing):

  • If you have a mapping (explicit or implicit), then you get the default value for that type (e.g., default(int))
  • If you don't supply a mapping, and there is no implicit automapping that will work, and you don't supply a value in the Destination class's constructor, then you get the default value for that type
  • If you don't supply a mapping, and there is no implicit automapping that will work, and you do supply a value in the Destination class's constructor, then you get the value that you specified in the constructor

Steps to reproduce

N/A

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

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions