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())
;
});
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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With