Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore mapping one property with Automapper

I'm using Automapper and I have the following scenario: Class OrderModel has a property called 'ProductName' that isn't in the database. So when I try to do the mapping with:

Mapper.CreateMap<OrderModel, Orders>();  

It generates an exception :

"The following 1 properties on Project.ViewModels.OrderModel are not mapped: 'ProductName'

I've read at AutoMapper's Wiki for Projections the opposite case (the extra attribute is on the destination, not in the source which is actually my case )

How can I avoid automapper to make the mapping of this property?

like image 923
Msam85 Avatar asked Feb 14 '11 00:02

Msam85


People also ask

How do I ignore property mapping in AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

Does AutoMapper map both ways?

Yes, or you can call CreateMap<ModelClass, ViewModelClass>(). ReverseMap() .

Does AutoMapper map private properties?

AutoMapper will map property with private setter with no problem. If you want to force encapsulation, you need to use IgnoreAllPropertiesWithAnInaccessibleSetter. With this option, all private properties (and other inaccessible) will be ignored.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.


2 Answers

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

like image 174
smartcaveman Avatar answered Sep 17 '22 21:09

smartcaveman


I'm perhaps a bit of a perfectionist; I don't really like the ForMember(..., x => x.Ignore()) syntax. It's a little thing, but it matters to me. I wrote this extension method to make it a bit nicer:

public static IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>(     this IMappingExpression<TSource, TDestination> map,     Expression<Func<TDestination, object>> selector) {     map.ForMember(selector, config => config.Ignore());     return map; } 

It can be used like so:

Mapper.CreateMap<JsonRecord, DatabaseRecord>()         .Ignore(record => record.Field)         .Ignore(record => record.AnotherField)         .Ignore(record => record.Etc); 

You could also rewrite it to work with params, but I don't like the look of a method with loads of lambdas.

like image 35
Steve Rukuts Avatar answered Sep 16 '22 21:09

Steve Rukuts