自动映射器成员忽略不起作用
本文关键字:不起作用 成员 映射 | 更新日期: 2023-09-27 18:37:21
在
MVC 应用中复制相同的实体类型,但希望忽略复制主键(对现有实体进行更新)。但是在下面的地图中将 Id 列设置为忽略是行不通的,并且 Id 被覆盖。
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);
看到了另一个答案,但似乎我已经在这样做了。
更新:
仅供参考,我正在 Global.asax 中创建我的地图,如下所示:
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())
;
});
您的问题是您没有向自动映射器提供现有对象。自动映射器绝对可以做到这一点。
Mapper.Map<VendorContact>(vendorContact, existingStratusVendorContact);
应该做你想做的事。您当前的代码正在创建一个全新的对象,并将existingStratusVendorContact
替换为全新的对象。上面的代码将采用现有对象并更新值,如您所料。
更新:
问题是,当您将Mapper.Map<VendorContact>(vendorContact);
分配给existingStratusVendorContact
时,无论您忽略了什么属性,都将变量的当前值替换为返回的 by Map()
方法。
使用 Mapper.Map(source)
可以根据某些约定将对象投影到复制属性的其他类型的新对象,但您正在创建新对象。
在代码中,您将创建一个具有 Id
、 CreatedById
和 CreatedOn
属性及其默认值的新对象。
您可以使用Mapper.Map(source, destination)
重载来执行您想要的操作:
Mapper.Map<VendorContact>(vendorContact, existingStratusVendorContact);
源语言:
如果要像这样创建地图:
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
则使用默认行为并映射属性。