1

How to get the type of the source member when using ForAllMembers?

E.g. when doing

public MapperConfiguration CreateMapperConfiguration<TSource, TDestination>()
{
    return new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<TSource, TDestination>().ForAllMembers(memberOptions =>
        {
            memberOptions.Condition((source, destination, sourceMemberValue, destinationMemberValue, resolutionContext) =>
            {
                if (sourceMemberValue == null)
                {
                    // How to get the type of the source member here?                    
                    // ResolutionContext.SourceType and ResolutionContext.DestinationType don't exist.
                }
                else
                {
                  var type = sourceMemberValue.GetType();

                  // How to find out if the type is a nullable type?
                  // The CLR converts int? to int when the value is boxed
                  // (which happens with sourceMemberValue since its
                  // static type is object).
                }                

                return true;
            });
        });

    });
}

Getting the source member type from ResolutionContext was possible via SourceType property in version 4 but this property doesn't exist anymore.

I checked the Upgrade guide but didn't find anything about this breaking change.

IMemberConfigurationExpression (received as memberOptions) has a DestinationMember property (of type MemberInfo) so the destination member type is available here (e.g. when casting MemberInfo to PropertyInfo) but there is no SourceMember property.

user764754
  • 3,865
  • 2
  • 39
  • 55

1 Answers1

0

The absence of IMemberConfigurationExpression.SourceMember is indeed felt. This hack relies on the source and destination members having the same name:

var sourceMember = typeof(TSource).GetMember(memberOptions.DestinationMember.Name);

From there you can discover its type. If you know the member is a property, you can simplify:

var sourceProp = typeof(TSource).GetProperty(memberOptions.DestinationMember.Name);
var sourceType = sourceProp?.PropertyType;

Then you can test if it's a Nullable<T>.

Kevin Krumwiede
  • 9,868
  • 4
  • 34
  • 82