Prolog
Prolog

Reputation: 3374

How to configure AutoMapper to not check the member list while mapping?

I'm creating maps like below while passing member list option to None:

CreateMap<Level, LevelVM>(MemberList.None);

But I don't want to do it for every map I create. I'd like to have this setting applied globally, as default. Is there a way to achieve this?

Upvotes: 2

Views: 5446

Answers (1)

SUNIL DHAPPADHULE
SUNIL DHAPPADHULE

Reputation: 2873

By default, AutoMapper tries to map all properties of the source type to the destination type. If some of the properties are not available in the destination type it will not throw an exception when doing the mapping. However, it will throw an exception when you are using ValidateMapperConfiguration().

  class SourceType
    {
        public string Value1 { get; set; }
    }


class DestinationType
{    
    public string Value1{ get; set; }
    public string Value2{ get; set; }
}

AutoMapper.AutoMapperConfigurationException : The following 1 properties on DestinationType are not mapped: Value2 Add a custom mapping expression, ignore, or rename the property on SourceType.

You can override this behavior by making Global setting to ignore all properties that do not exist on the target type. You can do setting over class level or property level or global like as I said

Simply add below code in Global.asax

Mapper.Initialize(cfg =>
    {
       cfg.ValidateInlineMaps = false
    }

At property, level ignores the Value2 property while doing the mapping between these two objects. To do so we need to use the AutoMapper Ignore Property with the Address property of

config.CreateMap<SourceType,DestinationType>()
                    //Ignoring the Value2  property of the destination type
                    .ForMember(dest => dest.Value2 , act => act.Ignore());

Upvotes: 2

Related Questions