Search code examples
c#automapperautomapper-4

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


Solution

  • 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.