Skip to content

Nullable properties on source being cast before conditional function called #1703

Closed

Description

@CicerosPatience

I'm writing a restful api and in my use case I am trying to map a nullable type on my source to a non-nullable property on my destination. I want it to ignore mapping properties if the source value is null. I want this because it is a really elegant solution for me to deserialize a partial json request into my object and only update fields on my entity object that were actually passed to my dto. See my code below (note, I've removed all my Entity Framework junk).

These are my source (ScriptDto) and destination (Script) classes.

public class ScriptDto
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        [JsonConverter(typeof(StringEnumConverter))]
        public ScriptLanguage? Language { get; set; }
        public string Target { get; set; }
        public string ScriptBody { get; set; }
        public DateTime? LastExecuted { get; set; }
        public Guid? LastExecutedBy { get; set; }
    }

 public class Script : IEntity
    {
        public Guid Id { get; private set; }
        public string Name { get; set; }
        public ScriptLanguage Language { get; set; }
        public string Target { get; set; }
        public string ScriptBody { get; set; }
        public DateTime LastExecuted { get; set; }
    }

This is my web api routed method

[HttpPut("{id}")]
public IActionResult UpdateScript(string id, [FromBody]ScriptDto scriptDto, [FromServices]IDatabaseConfigurationLoader loader)
   {
                Script script = //code to get my script object from the database
                if (script == null) { return NotFound(); }

                 var config = new MapperConfiguration(cfg => {
                    cfg.CreateMap<ScriptDto, Script>()
                       .ForMember(y => y.Id, opt => opt.Ignore())
                       .ForAllOtherMembers(opt =>
                       {
                           opt.Condition((src, dest, srcValue) =>
                           {
                               return srcValue != null; //ignore properties on dto that are null
                           });
                       });
                   });

                _mapper = config.CreateMapper();
                //map dto to entity
                _mapper.Map(dto, script);

                //save changes to database

                return new ObjectResult(MapToDto(script)); //return updated object
   }

What I would expect to happen with this, is if the source property is null the condition function evaluates to false and the property mapping is skipped. That is not what is happening for the nullable properties on my source object. After setting a break point inside the conditional function I realized that my source property values were being cast to the destination type (I assume) before they are passed to the conditional function. So where I would expect "srcValue" to be null it was actually already cast to its non-nullable default. If for example, I sent the following json PUT request to my service at api/v1/scripts/somescriptid

{ "scriptBody": "test body" }

then it would deserialize into a DTO object with mostly null properties, with the exception of the ScriptBody property. But when it gets mapped to my destination object, the DateTime? LastExecuted property which is null (for example) has its value cast to a non-nullable DateTime prior to being passed to the conditional function. Which of course causes my conditional function to evaluate to true and thus the destination property is overwritten.

I imagine I am having this issue because I am trying to map a nullable property on my source to a non-nullable property on my destination. When I change the property on my destination object to a nullable type then it works the way I would expect. That said, I do not want nullable types where they aren't required on my entity object. I'm using the latest dev build on myget, 5.2.0-alpha-01223.

Activity

  1. lbargaoanu commented on Sep 28, 2016

    @lbargaoanu
    Contributor

    I don't think this is going to happen. It might break a lot of people.

  2. CicerosPatience commented on Sep 28, 2016

    @CicerosPatience
    Author

    I get that it is probably a breaking change, but I also think its the correct way to do this. The only value I see to casting the source property before its passed into the conditional function is that it validates that the properties to be mapped are of the same type. If that's necessary, it can certainly be handled in a better way, either as a separate option or by the developer handling it inside the conditional function.

    Alternatively, I would suggest adding a separate function to options that allows this to be done. As it is, there is no other way that I am aware of to accomplish this use case with automapper.

  3. lbargaoanu commented on Sep 28, 2016

    @lbargaoanu
    Contributor

    You can check against the default value for the value type, but that's not exposed right now through the interface, so you need a cast.
    Update : no need for a cast anymore.

            cfg.CreateMap<Source, Destination>()
                    .ForAllOtherMembers(opt =>opt.IgnoreSourceWhenDefault());
    
    public static class Extensions
    {
        public static void IgnoreSourceWhenDefault<TSource, TDestination>(this IMemberConfigurationExpression<TSource, TDestination, object> opt)
        {
            var destinationType = opt.DestinationMember.GetMemberType();
            object defaultValue = destinationType.GetTypeInfo().IsValueType ? Activator.CreateInstance(destinationType) : null;
            opt.Condition((src, dest, srcValue) =>!Equals(srcValue, defaultValue));
        }
    	
        public static Type GetMemberType(this MemberInfo memberInfo)
        {
           if (memberInfo is MethodInfo)
               return ((MethodInfo)memberInfo).ReturnType;
           if (memberInfo is PropertyInfo)
               return ((PropertyInfo)memberInfo).PropertyType;
           if (memberInfo is FieldInfo)
               return ((FieldInfo)memberInfo).FieldType;
           return null;
        }
    }
    
  4. lbargaoanu commented on Sep 28, 2016

    @lbargaoanu
    Contributor

    @jbogard Maybe include this in AM? People seemed to want similar things before.

  5. jbogard commented on Oct 5, 2016

    @jbogard
    Contributor

    What's not exposed? Just the member?

  6. lbargaoanu commented on Oct 5, 2016

    @lbargaoanu
    Contributor

    Yes, the destination member type. But the final code doesn't look that bad :)

  7. alex-yakovenko commented on Nov 6, 2016

    @alex-yakovenko

    This bug appears when you use retrieved via NuGet instance of AutoMapper.dll. In this case added by Condition method expression obtains wrong value in sourceValue parameter. The bug disappeared after I rebuilt AutoMapper on local machine.

    Here is test code which I use to reproduce the bug:

    public class ConditionalParams
        {
    
            public interface ITestEntity
            {
                int ValueX { get; set; }
            }
    
            public class TestClassA : ITestEntity
            {
                private int _valueX;
    
                public int ValueX
                {
                    get { return _valueX; }
                    set { _valueX = value; }
                }
    
            }
    
            public class TestClassB : ITestEntity
            {
                private int _valueX = 7;
    
                public bool Updated = false;
    
                public int ValueX
                {
                    get { return _valueX; }
                    set
                    {
                        _valueX = value;
                        Updated = true;
                    }
                }
    
            }
    
            [Test]
            public void TestMapper()
            {
    
                Mapper.Initialize(cfg =>
                {
                    cfg.CreateMap<ITestEntity, TestClassB>().MapOnlyIfDirty();
                });
    
                var a = new TestClassA
                {
                    ValueX = 7
                };
    
                var b = new TestClassB();
    
                Mapper.Map(a, b);
    
                Assert.IsFalse(b.Updated);
            }
    
        }
    
        public static class MapperExtensions
        {
            public static IMappingExpression<TSource, TDestination> MapOnlyIfDirty<TSource, TDestination>(
                this IMappingExpression<TSource, TDestination> map)
            {
                map.ForAllMembers(source =>
                {
                    source.Condition((s, d, sourceValue, destValue, rc) =>
                    {
                        if (sourceValue == null)
                            return destValue != null;
                        return !sourceValue.Equals(destValue);
                    });
                });
                return map;
            }
        }
    
  8. lbargaoanu commented on Nov 6, 2016

    @lbargaoanu
    Contributor

    Most likely #1634. You can use the MyGet build instead.

  9. lbargaoanu commented on Dec 7, 2016

    @lbargaoanu
    Contributor

    The solution is above. CreateMissingTypeMaps is gonna get you into trouble eventually.

  10. lbargaoanu commented on Dec 7, 2016

    @lbargaoanu
    Contributor

    Then I guess you should try something else.

  11. lbargaoanu commented on Dec 7, 2016

    @lbargaoanu
    Contributor

    Or a PR. @jbogard seems OK with it.

  12. 32 remaining items

  13. lbargaoanu commented on Feb 11, 2017

    @lbargaoanu
    Contributor

    You need a condition for that. The comment was only for that particular case. Cargo cult programming won't get you anywhere.

  14. krishnandusarkar commented on Feb 11, 2017

    @krishnandusarkar

    @lbargaoanu Well, this is what I was asking. What kind of condition should I put in there? Do I need another resolver for string? Or I can plug the code in same Resolver. Sorry, but I do not get the approach.

  15. levitatejay commented on May 9, 2017

    @levitatejay

    Here is a solution that works with ForAllMembers if all the properties have the same names between objects

        class IgnoreNullSourceValues : IMemberValueResolver<object, object, object, object>
        {
            public object Resolve(object source, object destination, object sourceMember, object destinationMember, ResolutionContext context)
            {
                return sourceMember ?? destinationMember;
            }
        }
    

    and use it like so:

    cfg.CreateMap<SourceObject, DestObject>()
                    .ForAllMembers(a => a.ResolveUsing<IgnoreNullSourceValues, object>(a.DestinationMember.Name));
    
  16. GFoley83 commented on Oct 3, 2017

    @GFoley83

    @levitatejay How would I update your Resolve method to allow for the scenario when there's no destination / source member to map to? E.g. if my source object doesn't have a property that the destination has.

  17. petrosmm commented on May 11, 2018

    @petrosmm

    in #1703 (comment) @lbargaoanu used Nullable.GetUnderlyingType(pm.SourceType) why would he/she have needed to use that method instead of just using pm.SourceType; I am not sure I understand the intent by it? Also if I used pm.SourceType.UnderlyingSystemType instead what issue could I run into?

  18. lbargaoanu commented on May 12, 2018

    @lbargaoanu
    Contributor

    Because this happens only in this particular case, for the rest, the source member is null as expected.

  19. Yon2068 commented on Aug 2, 2018

    @Yon2068

    This is an extension

    Works for all Nullable types

    How to use it?

    AutoMapper.Mapper.Initialize(cfg => { cfg.IgnoreSourceWhenNull(); });

    Here's the extension

    AutoMapperExtensions.cs.zip

  20. lbargaoanu commented on Aug 3, 2018

    @lbargaoanu
    Contributor

    You don't need more than one instance of that resolver. You can create it in your extension and pass that instance.

  21. Yon2068 commented on Aug 3, 2018

    @Yon2068

    @lbargaoanu
    With this extension:
    ObjectId can't convert to string
    How do I do that?

  22. lbargaoanu commented on Aug 3, 2018

    @lbargaoanu
    Contributor

    I have no idea what you're saying.

  23. Yon2068 commented on Aug 3, 2018

    @Yon2068

    @lbargaoanu
    System.InvalidCastException : Unable to cast object of type 'MongoDB.Bson.ObjectId' to type 'System.String'.

  24. lbargaoanu commented on Aug 3, 2018

    @lbargaoanu
    Contributor

    That's most likely an issue with your own code.

  25. Yon2068 commented on Aug 3, 2018

    @Yon2068

    I using ForAllPropertyMaps to ignore all Nullable<>
    ForAllPropertyMaps()

    var isNullable = pm.SourceType.IsGenericType 
    && (pm.SourceType.GetGenericTypeDefinition() == typeof(Nullable<>));
    return isNullable || pm.SourceType.IsClass || pm.SourceType.IsValueType || pm.SourceType.IsPrimitive;

    Resolve()

    return sourceMember ?? destinationMember;
  26. lock commented on May 6, 2019

    @lock

    This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

  27. locked as resolved and limited conversation to collaborators on May 6, 2019
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

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions