ForMember忽略不起作用

ForMember忽略不起作用

本文介绍了AutoMapper ForMember忽略不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC应用中执行相同实体类型的副本,但希望忽略复制主键(对现有实体进行更新).但是将Id列设置为在下面的地图中忽略不起作用,并且Id正在被覆盖.

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

执行地图:

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

看到了其他答案,但看来我在做什么已经.

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

更新:

好,我正在像这样在Global.asax中创建地图:

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

});

推荐答案

您的问题是您没有给automapper现有的对象. Automapper绝对可以做到这一点.

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

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

应该做你想做的.您当前的代码正在创建一个全新的对象,并用全新的对象替换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.

这篇关于AutoMapper ForMember忽略不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 07:49