Skip to content

Dynamic map of base class influences child class map #3025

@matthiaslischka

Description

@matthiaslischka

Hi,
we stumbled across some odd behavior with dynamic maps.

void Main()
{
    AutoMapper.Mapper.Reset();
    AutoMapper.Mapper.Initialize(cfg => 
        { 
            cfg.CreateMissingTypeMaps = true; 
            cfg.ValidateInlineMaps = false; 
        }); 

    var model = new Model { Name = "Matthias", VersionNumber = 123 };

    var bar = AutoMapper.Mapper.Map(model, new Bar());
    var foo = AutoMapper.Mapper.Map(model, new Foo()); //VersionNumber null because BaseClass Bar was mapped before and does not have property VersionNumber. Comment out the line above and VersionNumber will be 123
		
    bar.Dump();
    foo.Dump();
}

class Model {
    public string Name {get; set;}
    public long VersionNumber {get; set;}
}

class Bar {
    public string Name {get;set;}
}

class Foo : Bar {
    public long? VersionNumber {get; set;}
}

foo.VersionNumber will be null when I call a dynamic map on the base class before and set to 123 when I don't. That's strange to me.
When I try the same with types and not concrete objects it throws an exception. I guess because the dynamically generated map for the base class Bar can not be used for Foo. But the exception message is strange.

var bar = AutoMapper.Mapper.Map<Bar>(model);
var foo = AutoMapper.Mapper.Map<Foo>(model);

// InvalidCastException: Unable to cast object of type 'Bar' to type 'Foo'.

We already learned that we will not use dynamic maps anymore. Just wanted to share our findings and ask if this behavior is intentional or a unknown side effect.

Thanks and BR Matthias

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