Ignore Mapping One Property with Automapper

Ignore mapping one property with Automapper

From Jimmy Bogard: CreateMap<Foo, Bar>().ForMember(x => x.Blarg, opt => opt.Ignore());

It's in one of the comments at his blog.

UPDATE(from Jamie's comment Jan 4 '19 at 11:11:)

Ignore has been replaced with DoNotValidate in ForSourceMember:
https://github.com/AutoMapper/AutoMapper/blob/master/docs/8.0-Upgrade-Guide.md

Ignore a property in AutoMapper?

On your Mapper.CreateMap<Type1, Type2>() you can use either

.ForSourceMember(x => x.Id, opt => opt.Ignore())

or

.ForMember(x => x.Id, opt => opt.Ignore())

UPDATE:
It seems like .Ignore() is renamed to .DoNotValidate() according to the AutoMapper docs.

How to ignore property of property in AutoMapper mapping?

This should just work. See https://github.com/AutoMapper/AutoMapper/wiki/5.0-Upgrade-Guide#circular-references. There is also a PR pending https://github.com/AutoMapper/AutoMapper/pull/2233.

Ignore property with automap IF something

You can use the Ignore() feature to strict members you will never map but these members are will be skipped in configuration validation.

What you might find usefull to use is the Condition() feature so you can map the member when the condition is true like the example below:

var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo,Bar>()
.ForMember(dest => dest.baz, opt => opt.Condition(src => (src.baz >= 0)));
});

In the above mapping example the property baz will only be mapped if it is greater than or equal to 0 in the source object.

With AutoMapper how do I ignore a destination property that does not have an accessible getter

Use the ForMember overload that takes name of the property as parameter.

.ForMember("nameSpecial", src=>src.Ignore())

Automapper map a few and ignore the rest

We ran into the same issue. I created this extension method which should provide the functionality you're looking for.

public static IMappingExpression<TSource, TDestination> IgnoreAllMembers<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expr)
{
var destinationType = typeof(TDestination);

foreach (var property in destinationType.GetProperties())
expr.ForMember(property.Name, opt => opt.Ignore());

return expr;
}

The usage for it:

CreateMap<ModelOne, ModelTwo>()
.IgnoreAllMembers()
.ForMember(x => x.DescriptionOne, opt => opt.MapFrom(y => y.DescriptionOne));

It works by looping through all the properties of the destination type and ignoring them. This means it needs to be called before you provide your member mappings. Calling it after will override your mappings.

Hope this helps.

How to ignore properties of a specific type when using Automapper?

You can use ShouldMapProperty in your config:

 cfg.ShouldMapProperty = p => p.PropertyType != typeof(string);

Official docs on this here. Original feature request by yours truly.



Related Topics



Leave a reply



Submit