AutoMapper ForMember does not work

Executing a copy of the same entity type in an MVC application, but ignoring copying the primary key (updating an existing object). But setting the Id column to ignore on the map below does not work, and the ID is 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())
    ; 

Card Execution:

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

Saw this other answer , but it looks like I'm already doing it.

UPDATE:

Fyi, I create my maps in Global.asax like this:

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())
        ;  

});
+4
source share
2 answers

Your problem is that you are not giving the automapper an existing object. Automapper can do this absolutely.

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

, . existingStratusVendorContact . , .

+2

UPDATE:

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

Mapper.Map(source) , .

Id, CreatedById CreatedOn .

Mapper.Map(source, destination), , :

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

ORIGINAL:

:

var cfg = new MapperConfiguration(c =>
{
    c.CreateMap<VendorContact, VendorContact>()
        .ForMember(dest => dest.Id, option => option.Ignore())
        .ForMember(dest => dest.CreatedById, option => option.Ignore())
        .ForMember(dest => dest.CreatedOn, option => option.Ignore());
});

:

var mapper = cfg.CreateMapper();

:

var existingStratusVendorContact = mapper.Map<VendorContact>(vendorContact);

Mapper, .

0

All Articles