15

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

2 Answers 2

22

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

UPDATE: It seems like .Ignore() is renamed to .DoNotValidate() according to the AutoMapper docs.

5
  • sorry where I can find Mapper.CreateMap ? I just have installed in using Nuget packages and the line of code I added in question is only line I did.
    – user576510
    Nov 12, 2014 at 23:19
  • 1
    @user576510 It should just be under the AutoMapper namespace. Just create that on its own line (followed by .ForMember() or .ForSourceMember() depending on how you are binding) and you should be good to go :)
    – John
    Nov 12, 2014 at 23:26
  • @John Why I need to use Ignore? Properties which are missing in a destination type will get their default value. Mar 3, 2017 at 15:29
  • @JosephKatzman I dunno maybe its changed in the last 2 years ;)
    – John
    Mar 4, 2017 at 6:45
  • @JosephKatzman: opt.Ignore() tells AutoMapper to not map a value to that destination member. AutoMapper maps to destination members by default so, if there is no destination member, the member doesn't get mapped anyway (and should generate a compiler error). If the destination does contain the member, AutoMapper tries to find a source member to map from, unless you use Ignore().
    – Suncat2000
    May 14, 2020 at 13:20
1

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.

2
  • thanks, I m new to automapper, do i need add some configurations in config file ? I only have done line of code which I mention in qeustion. Wehre I should use Mapper.CreateMap ?
    – user576510
    Nov 12, 2014 at 23:24
  • When your app initializes, you need to call a Initialize method that will setup all the mappings of your classes. See this guide to know more Automapper github.com/AutoMapper/AutoMapper/wiki/Getting-started.
    – Omar.Alani
    Nov 12, 2014 at 23:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.