Skip to content

Bug in using Include to map derived classes #3069

@joakimgk

Description

@joakimgk

Source/destination types

public class Destination 
{
   public string Field { get; set; }
}

public class Source
{
}

public class DerivedSource : Source
{
}

Mapping configuration

CreateMap<DerivedSource, Destination>();

CreateMap<Source, Destination>()
  .Include<DerivedSource, Destination>()
  .ForMember(dest => dest.Field, opts => opts.Ignore());

Version: 8.1.0

Expected behavior

In AutoMapper 6.2.2, mapping inheritance worked regardless of ordering of CreateMap calls. However, after upgrading to version 8 we have to make sure that any derived types are declared after the base class which Includes these same base types. The above example fails (AssertConfigurationIsValid in the MapperConfiguration throws an AutoMapperConfigurationException) because Include<DerivedSource, Destination>() is done after CreateMap<DerivedSource, Destination>(). If the maps are created in opposite order (i.e. do CreateMap<Source, Destination>() first) the mapping works as intended.
Interestingly, ordering does not appear to be relevant when using IncludeBase . This seems to indicate that this is a bug with Include, and not an intentional (breaking) change with version 8?

Actual behavior

AutoMapper.AutoMapperConfigurationException :
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
DerivedSource -> Destination (Destination member list)

Unmapped properties:
Field3

Steps to reproduce

// Your calls to Mapper.Map or ProjectTo here, with source/destination objects constructed

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions