Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper ForMember Ignore not working

Tags:

c#

automapper

Doing a copy of the same entity type in an MVC app, but looking to ignore copying the primary key (doing an update to an existing entity). But setting the Id column to ignore in the map below is not working and the Id is being overwritten.

cfg.CreateMap<VendorContact, VendorContact>()
    .ForMember(dest => dest.Id, option => option.Ignore())
    .ForMember(dest => dest.CreatedById, option => option.Ignore())
    .ForMember(dest => dest.CreatedOn, option => option.Ignore())
    ; 

Executing the Map:

existingStratusVendorContact = Mapper.Map<VendorContact>(vendorContact);

Saw this other answer, but it appears I am doing that already.

UPDATE:

Fyi, I am creating my maps in the Global.asax like so:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<VendorContact, VendorContact>()
        .ForMember(dest => dest.Id, option => option.Ignore())
        .ForMember(dest => dest.CreatedById, option => option.Ignore())
        .ForMember(dest => dest.CreatedOn, option => option.Ignore())
        ;  

});
like image 620
crichavin Avatar asked Mar 03 '16 22:03

crichavin


People also ask

How do I ignore property 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.

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

How does AutoMapper work in C#?

AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.

Is AutoMapper fast?

Automapper is slower when mapping a single object and collections but there is one exception. Automapper is considerably faster when mapping a List<T> of objects on . NET Core (It's still slower on full .


1 Answers

Your issue is that you're not giving automapper the existing object. Automapper can absolutely do this.

Mapper.Map<VendorContact>(vendorContact, existingStratusVendorContact);

Should do what you want. You current code is creating a brand new object, and replacing existingStratusVendorContact with the entirely new object. The above code will take the existing object and update values, as you expected.

like image 164
Thomas Boby Avatar answered Nov 11 '22 13:11

Thomas Boby