Search code examples
c#automapper.net-6.0

Why does AutoMapper validation not work if an object Property exists?


If I call the AssertConfigurationIsValid() function of AutoMapper it should throw an exception for each property of a mapped class, that uses a type that is not mapped. It seems like this does not happen, if at least one of the properties is of type object.

I understand that AutoMapper cannot check, if everything that can be assigned to a object property is mapped, but I assumed it would still throw an exception for other properties that use unmapped types.

If I have these simple classes:

public class RootLevel
{
    public object ObjectProperty { get; set; }
    public SecondLevel SecondLevel { get; set; }
}

public class RootLevelDto
{
    public object ObjectProperty { get; set; }
    public SecondLevelDto SecondLevel { get; set; }
}

public class SecondLevel
{
}

public class SecondLevelDto
{
}

And I (incorrectly) only map the RootLevel class and try to execute this code:

var config = new MapperConfiguration(config =>
{
    config.CreateMap<RootLevel, RootLevelDto>();
});
config.AssertConfigurationIsValid();
var mapper = new Mapper(config);

var source = new RootLevel
{
    SecondLevel = new SecondLevel()
};
var mapped = mapper.Map<RootLevelDto>(source);

I would expect the call to config.AssertConfigurationIsValid() to throw an exception because the type SecondLevel is not mapped. But I only get the exception as soon as I call mapper.Map<RootLevelDto>(source), and only if my source object actually has a non-null value in the SecondLevel property.

If I comment out the ObjectProperty properties, the call to AssertConfigurationIsValid() throws the expected exception.

This lead to an issue where I discovered missing mappings too late, because the value was always null during testing.

Is there a way to avoid this issue, other than getting rid of the object properties?


Solution

  • That's a bug, solved now. Try the MyGet build.

    A fragile workaround is to declare the object properties at the end of the class definition.