Ignore a property in AutoMapper?

不打扰是莪最后的温柔 提交于 2019-12-21 09:36:17

问题


I'm using Automapper to copy one object properties to other and later will update in database using EF.

Question is how to tell Automapper copy every property but ignore a particular property (in this case it will be Id). I'm new to AutoMapper and just have done this code. I don't have other configurations or use of AutoMap in project.

Mapper.Map(lead, existingLead);

I have downloaded AutoMapper form here https://github.com/AutoMapper/AutoMapper


回答1:


On your Mapper.CreateMap<Type1, Type2>() you can use either

.ForSourceMember(x => x.Id, opt => opt.Ignore())

or

.ForMember(x => x.Id, opt => opt.Ignore())



回答2:


I use this extension method:

public static IMappingExpression<TSource, TDestination> IgnoreMember<TSource, TDestination>(
    this IMappingExpression<TSource, TDestination> map, Expression<Func<TDestination, object>> selector)
{
    map.ForMember(selector, config => config.Ignore());
    return map;
}

and I use it like this

Mapper.CreateMap<MyType1, MyType2>().IgnoreMember(m => m.PropertyName);

Hope that helps.



来源:https://stackoverflow.com/questions/26898442/ignore-a-property-in-automapper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!