Can you tell AutoMapper to globally ignore missing properties when mapping?

Suggested in wal's answer "don't call AssertConfigurationIsValid()" is not safe, as it will hide potential errors in mappings.
It's better to explicitly ignore mapping between classes, for which you are sure that all needed properties already mapped correctly. You can use extensions created in AutoMapper: "Ignore the rest"? answer:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Src, Dest>();
     cfg.IgnoreUnmapped<Src, Dest>();  // Ignores unmapped properties on specific map
});

The overload without parameters cfg.IgnoreUnmapped(this IProfileExpression profile) ignores unmapped properties on all maps and not recommended, because it also hides any potential problems for all classes.


When are you getting the error? Is it when you call AssertConfigurationIsValid ?

If yes, then simply dont call this method

You dont have to call this method, consider the following mapping which works:

public class Foo1
{
    public string Field1 { get; set; }
}
public class Foo2
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

Mapper.CreateMap<Foo1, Foo2>();
var foo1 = new Foo1() {Field1 = "field1"};
var foo2 = new Foo2();
Mapper.Map(foo1, foo2);//maps correctly, no Exception

You may want to call AssertConfigurationIsValid for other mappings to ensure they are correct so instead what you need to do is organize your mappings into Profiles:

public class MyMappedClassesProfile: Profile
{
    protected override void Configure()
    {
        CreateMap<Foo1, Foo2>();
        //nb, make sure you call this.CreateMap and NOT Mapper.CreateMap
        //I made this mistake when migrating 'static' mappings to a Profile.    
    }
}

Mapper.AddProfile<MyMappedClassesProfile>();

and then if you decide you want to check the validity of the mapping (case by case basis in your situation) then call

Mapper.AssertConfigurationIsValid(typeof(MyMappedClassesProfile).FullName);

important in your case and/or any case where you dont call AssertConfigurationIsValid you should use something like AutoFixture and a Unit Test to ensure your mapping is working. (which is the intent of AssertConfigurationIsValid)

Tags:

C#

Automapper