Ignore mapping for all members with different types and same name, using newest version of Automapper(6.1.1)

541 Views Asked by At

How can I ignore mapping if some properties have different type with same name? By default it's throwing error. I found some answers for an older versions of automapper but they are not working with the newest.

For example one property is string the other is bool but they both have the same name. The behaviour i want is to ignore them(not try to map them).

1

There are 1 best solutions below

3
On BEST ANSWER

Here is a small example based on this link

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<Class1, Class2>();

    cfg.ForAllMaps((typeMap, mappingExpr) =>
    {
        var ignoredPropMaps = typeMap.GetPropertyMaps();

        foreach (var map in ignoredPropMaps)
        {
            var sourcePropInfo = map.SourceMember as PropertyInfo;
            if (sourcePropInfo == null) continue;
            if (sourcePropInfo.PropertyType != map.DestinationPropertyType)
                map.Ignored = true;
        }
    });
});

Class1 src = new Class1()
{
    TestProperty = "A"
};
Class2 dest = Mapper.Map<Class1, Class2>(src);

Test classes:

public class Class1
{
    public string TestProperty { get; set; }
}

public class Class2
{
    public bool TestProperty { get; set; }
}