Ignore property in AutoMapper?

I use Automapper to copy the properties of one object to another, and will later be updated in the database using EF.

The question is how to tell Automapper to copy each property, but ignore a specific property (in this case it would be Id). I am new to AutoMapper and just made this code. I have no other configurations or using AutoMap in the project.

Mapper.Map(lead, existingLead); 

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

+5
source share
2 answers

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

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

or

 .ForMember(x => x.Id, opt => opt.Ignore()) 
+6
source

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 that

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

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1206753/


All Articles