Fab
Fab

Reputation: 14813

Automapper doesn't map properly on hierarchy

I'm using Automapper to copy interfaces to different implementations (for serialization, for view model, for database mapping, etc...).

My code is a lot more complex but I've isolated the problem in the following code snippet sample.

Considering the following code, do I miss something because the second assertion is failing:

    [Test]
    public void AutoMapperTest()
    {
        Mapper.CreateMap<IMyBaseInterface, MyClass>();
        Mapper.CreateMap<IMyInterface, MyClass>();            
        IMyBaseInterface baseInstance = new MyBaseClass{ MyBaseProperty = "MyBase" };
        var concrete = Mapper.Map<MyClass>(baseInstance);
        concrete.MyClassProperty = "MyClass";
        MyClass mapped = Mapper.Map<IMyInterface,MyClass>(concrete);
        Assert.AreEqual(concrete.MyBaseProperty, mapped.MyBaseProperty);
        Assert.AreEqual(concrete.MyClassProperty, mapped.MyClassProperty);
    }

Expected: "MyClass" But was: null

public class MyClass : MyBaseClass, IMyInterface
{
    public string MyClassProperty { get; set; }        
}

public interface IMyInterface : IMyBaseInterface
{
    string MyClassProperty { get; }        
}

public class MyBaseClass : IMyBaseInterface
{
    public string MyBaseProperty { get; set; }
}

public interface IMyBaseInterface
{
    string MyBaseProperty { get; } 
}

Environment:

Automapper : 4.1.1.0 / .Net: 4.5 / VS 2013

Upvotes: 1

Views: 506

Answers (2)

Andrew
Andrew

Reputation: 1534

If you are using inheritance and you want to combine this with Automapper you have to say Automapper that this class is base for these classes, and these classes are children of this class. I had the same problem and it started work only when I specified ALL my inheritance relationships

Its better to check this doc page about inheritance config

Upvotes: 1

Fab
Fab

Reputation: 14813

Work around: Add Mapper.CreateMap<MyClass, MyClass>();

I don't see the above as a real answer. Since it means that if I have several implementations, I have to create mappings for all combinations. And add another mapping if I write a new implementation, even if the whole time, they all implement the same interface.

Upvotes: 1

Related Questions