244

Is there a way to tell AutoMapper to ignore all of the properties except the ones which are mapped explicitly?

I have external DTO classes which are likely to change from the outside and I want to avoid specifying each property to be ignored explicitly, since adding new properties will break the functionality (cause exceptions) when trying to map them into my own objects.

Igor Brejc
  • 18,714
  • 13
  • 76
  • 95
  • 1
    with the ValueInjecter http://valueinjecter.codeplex.com/documentation you create ValueInjections that have their mapping alghorithm and map between specific properties, and they don't care about the rest of the properties – Omu May 05 '10 at 18:38
  • 32
    For those using Automapper > version 5, skip down to see answers detailing `.ForAllOtherMembers(opts => opts.Ignore())` – Jack Ukleja Oct 21 '16 at 00:48
  • 2
    @Schneider ".ForAllOtherMembers(opts => opts.Ignore())" is different with the extension "IgnoreAllNonExisting" here, the main difference is if you did not config property explicitly, with ".ForAllOtherMembers(opts => opts.Ignore())" you will get nothing mapped. use "IgnoreAllNonExisting" without config property explicitly, you still get some property mapped(properties with same name) with value. – Dragon Jan 13 '17 at 05:58
  • Yes. The ForAllOtherMembers is the answer. The IgnoreUnmapped answers don't do anything except cause the config-valid-assert to pass, because unmapped members are ignored anyway. – N73k Jun 02 '17 at 03:17
  • 1
    Worth noting that when doing this, you explicitly hide away potentially relevant or important changes in the classes being mapped. Having explicit mappings for every property will leave you with a broken test whenever the mapped class changes, forcing you to evaluate it properly. (Given that you have a test doing the `AssertConfigurationIsValid()` call) Because of this, I consider "Ignore the rest" an antipattern. – Arve Systad Sep 30 '19 at 09:53
  • The solution for AutoMapper 11 is https://stackoverflow.com/questions/72367321/automapper-map-a-few-and-ignore-the-rest/73333328#73333328 – Michael Freidgeim Jan 06 '23 at 18:34

18 Answers18

332

From what I understood the question was that there are fields on the destination which doesn't have a mapped field in the source, which is why you are looking for ways to Ignore those non mapped destination fields.

Instead of implementing and using these extension method you could simply use

Mapper.CreateMap<sourceModel, destinationModel>(MemberList.Source);  

Now the automapper knows that it needs to only validate that all the source fields are mapped but not the other way around.

You can also use:

Mapper.CreateMap<sourceModel, destinationModel>(MemberList.Destination);  
aochagavia
  • 5,887
  • 5
  • 34
  • 53
Nazim Hafeez
  • 3,329
  • 2
  • 10
  • 3
  • 13
    This answer should have more upvotes, maybe even be marked as the answer. It solved my problem and similarly `MemberList.Destination` would solve ops problem. – Tedd Hansen Jan 12 '16 at 12:25
  • 1
    It won't work if you want to ignore few properties on both source and destination :) – RealWillyWonka Jan 27 '16 at 22:05
  • @KManohar why would you want to ignore on both the source and destination? AutoMapper only validates one side or the other. – Jimmy Bogard Jun 28 '16 at 13:07
  • I agree with @Tedd; why mess around with custom extension methods (some of which use the old static API) when this one-liner does exactly what is required? – BCA Aug 23 '16 at 16:04
  • Excellent, thank you. Specifying a mapping direction is also important for unit testing--simply add unit test that calls Mapper.Configuration.AssertConfigurationIsValid()--and clearly indicating intention. Ignoring all unmapped properties on both source and destination is far too broad and would likely lead to bugs in production. – lightmotive Oct 05 '16 at 14:13
  • 83
    To anyone that comes later, THIS IS THE CORRECT ANSWER FOR 5.0 – Jimmy Bogard Dec 05 '16 at 20:16
  • The question is for AutoMapper 2.0. This does work for 5.0, but does it apply to the original question? – Chinemere Okereke Sep 20 '17 at 23:16
  • For a modern version of AutoMapper this is pretty much an ideal solution if all you are interested in is making sure that the mappings are satisfied for only one side of the comparison. – JSancho Dec 12 '17 at 16:02
  • 5
    looks nifty but did not work for me.. i tried Source and Destination, but it keeps complaining about the same property object missing a map – Sonic Soul Apr 06 '18 at 21:35
  • 4
    Using 6.0.2 and this doesn't work period. Any property that's not mapped from destination to source, overwrite the properties in source with nulls and 0s. Plus the code doesn't make it clear to what you're doing, especially if you're working in a team. That's why I heavily dislike this code, and why I prefer choice words like the suggested answer "IgnoreAllNonExisting" – sksallaj Sep 13 '18 at 20:06
  • 1
    Works, but I think you have the order of source and destination reversed in your examples? – dlf Aug 27 '19 at 18:41
  • 1
    In case you need to ignore extra properties `.ForSourceMember(src => src.Name, opt => opt.Ignore());` – Jaider Aug 06 '21 at 18:05
  • FWIW in @Jaider 's code I had to use `DoNotValidate` instead of `Ignore` – Jon.Mozley Feb 09 '22 at 09:44
  • This should be marked as correct answer as this infers the best practices using AutoMapper! – Vasil Popov Aug 04 '22 at 11:25
228

I've updated Can Gencer's extension to not overwrite any existing maps.

public static IMappingExpression<TSource, TDestination> 
    IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof (TSource);
    var destinationType = typeof (TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType));
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

Usage:

Mapper.CreateMap<SourceType, DestinationType>()
                .ForMember(prop => x.Property, opt => opt.MapFrom(src => src.OtherProperty))
                .IgnoreAllNonExisting();

UPDATE: Note that in Version 9.0 Mapper static API was removed

Michael Freidgeim
  • 26,542
  • 16
  • 152
  • 170
Robert Schroeder
  • 2,391
  • 2
  • 13
  • 6
  • 5
    +1, Thanks to you for posting this solution. It tooked me hours for figuring weird bug when I use solution in http://goo.gl/rG7SL, until I stumble to this post again. – Nordin Jul 13 '11 at 10:05
  • 2
    makes sense, seems like a more robust solution, updated my answer to point to yours. did not know of a method "GetUnmappedPropertyNames" :) – Can Gencer Aug 14 '11 at 07:03
  • 3
    Works with the static Mapper class. When you have your AutoMapper configured through IoC you need to get the IConfigurationProvider for getting all type maps. – Martijn B Apr 17 '13 at 17:38
  • 3
    I recommend Yohanb's method below over this. There are some corner cases that this doesn't work for it appears. – Jon Barker Aug 04 '14 at 14:00
  • @Nordin you used a URL shortening service to shorten a full URL which points to an answer above this one here... Is your code also that clever? – MarioDS Aug 12 '15 at 15:20
  • @MDeSchaepmeester It just out of habit from twittering on those years (2013) to shorten URL so that it will appear shorter, instead of displaying two or three lines of the link. It might or might not be relevant today. TQ for highlighting that to me. And yes, I do use StackOverflow because my code always not be seen ideal, and hope I could learn from other brilliant and nice people over here. Cheers. – Nordin Aug 14 '15 at 07:23
  • I've been using this for awhile and have found it does not work if you're doing testing and want to configure your own IMappingEngine. This is because this solution uses the static Mapper, which is an anti-pattern in itself. I recommend Yohanb's solution below to give better testability. – Ryan Langton Aug 28 '15 at 18:55
  • 4
    Can this be done in AutoMapper 4.2? (The `Mapper.GetAllTypeMaps()` is deprecated) – mrmashal Feb 13 '16 at 05:14
  • 1
    @mrmashal The AutoMapper 4.2 approach is described in [this answer](http://stackoverflow.com/a/35078700/145173). – Edward Brey Feb 22 '16 at 23:47
  • 16
    For AutoMapper 5+ version just replace `Mapper.GetAllTypeMaps()` with `Mapper.Configuration.GetAllTypeMaps()`. Here is the reference github.com/AutoMapper/AutoMapper/issues/1252 – SerjG Nov 03 '16 at 15:07
  • 1
    @Sergey - that doesn't work when you are using the new IMapper way. Throws this error: "Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance." – Hiral Desai Mar 02 '17 at 18:15
  • @HiralDesai this will not work for the ProjectTo() I guess. But it's out of the scope of the question – SerjG Mar 02 '17 at 19:40
  • 6
    For new people reading this. This answer is for AutoMapper 2 and at the time of writing this comment we are at version 6. This is a hack and a much cleaner way is using MemberList enum. See Github issue 1839 and a better solution. https://github.com/AutoMapper/AutoMapper/issues/1839 So example: https://stackoverflow.com/a/31182390/3850405 – Ogglas Jul 07 '17 at 09:06
105

Update: This answer is no longer useful to those using up to date versions of Automapper as ForAllOtherMembers has been removed in Automapper 11.


Version 5.0.0-beta-1 of AutoMapper introduces the ForAllOtherMembers extension method so you can now do this:

CreateMap<Source, Destination>()
    .ForMember(d => d.Text, o => o.MapFrom(s => s.Name))
    .ForMember(d => d.Value, o => o.MapFrom(s => s.Id))
    .ForAllOtherMembers(opts => opts.Ignore());

Be aware that there is an advantage to explicitly mapping each property as you will never get problems of mapping failing silently that arise when you forget to map a property.

Perhaps in your case it might be wise to ignore all other members and add a TODO to come back and make these explicit after the frequency of changes to this class settle down.

ajbeaven
  • 9,265
  • 13
  • 76
  • 121
  • 4
    Amazing this took until version 5. Look how many up -votes and attempted answers to this question...something wrong with Automapper's governance I wonder? – Jack Ukleja Oct 21 '16 at 00:49
  • Thank you for this, took me awhile to scroll down to it but this, but it works perfectly. – cobolstinks Feb 10 '17 at 14:44
  • 2
    You can even put the ForAllOtherMembers line first and things will work the same, which is good if you have some kind of base class configuration. – N73k Jun 02 '17 at 15:07
  • This is now the preferred approach. Wonder if the OP could change the accepted answer? – Chase Florell Nov 07 '17 at 23:52
  • 2
    Is there an equivalent to ignore the properties in the source object? Something like `ForAllOtherSourceMembers`? – SuperJMN Apr 04 '19 at 08:42
  • 1
    @SuperJMN there is `MemberList` enum, just place it in a `CreateMap` method as param like this: `CreateMap(MemberList.Source)` – akim lyubchenko Apr 08 '20 at 13:34
  • 2
    Even it answers the question, [Jimmy Bogard explained](https://stackoverflow.com/a/955607/52277) that ForAllOtherMembers(opts => opts.Ignore()) defeats the purpose of **Auto**mapper. Consider to use [IgnoreUnmapped()](https://stackoverflow.com/a/38073718/52277)to still have members mapped by convention and just avoid alert from AssertConfigurationIsValid() – Michael Freidgeim Feb 13 '21 at 22:25
  • ForAllOtherMembers extension method was removed from Automapper 11. If you still need it, see https://stackoverflow.com/questions/71311303/replacement-for-automappers-forallothermembers/74394201#74394201 – Michael Freidgeim Jan 06 '23 at 18:55
90

This is an extension method I wrote that ignores all non existing properties on the destination. Not sure if it will still be useful as the question is more than two years old, but I ran into the same issue having to add a lot of manual Ignore calls.

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
    var flags = BindingFlags.Public | BindingFlags.Instance;
    var sourceType = typeof (TSource);
    var destinationProperties = typeof (TDestination).GetProperties(flags);

    foreach (var property in destinationProperties)
    {
        if (sourceType.GetProperty(property.Name, flags) == null)
        {
            expression.ForMember(property.Name, opt => opt.Ignore());
        }
    }
    return expression;
}

Usage:

Mapper.CreateMap<SourceType, DestinationType>()
                .IgnoreAllNonExisting();

UPDATE: Apparently this does not work correctly if you have custom mappings because it overwrites them. I guess it could still work if call IgnoreAllNonExisting first and then the custom mappings later.

schdr has a solution (as an answer to this question) which uses Mapper.GetAllTypeMaps() to find out which properties are unmapped and auto ignore them. Seems like a more robust solution to me.

Can Gencer
  • 8,822
  • 5
  • 33
  • 52
87

I've been able to do this the following way:

Mapper.CreateMap<SourceType, DestinationType>().ForAllMembers(opt => opt.Ignore());
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*Do explicit mapping 1 here*/);
Mapper.CreateMap<SourceType, DestinationType>().ForMember(/*Do explicit mapping 2 here*/);
...

Note: I'm using AutoMapper v.2.0.

Yohanb
  • 871
  • 6
  • 2
  • 5
    thank you so much! it works like a charm. i tried first to chain the calls but ForAllMembers just return void :(. It wasn't obvious that a preceding IgnoreAll can be modified later. – SeriousM Oct 17 '12 at 12:00
  • 7
    I don't like this way either.. if you have 50 members, and you want to ignore 25.. then what's the point of automapper if you still gotta ignore 25 members. If names match, and there are properties that dont match.. why not make it clear to tell automapper to not match on unmapped properties and by passing all the typing? – sksallaj Sep 13 '18 at 20:08
45

As of AutoMapper 5.0, the .TypeMap property on IMappingExpression is gone, meaning the 4.2 solution no longer works. I've created a solution which uses the original functionality but with a different syntax:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Src, Dest>();
    cfg.IgnoreUnmapped();        // Ignores unmapped properties on all maps
    cfg.IgnoreUnmapped<Src, Dest>();  // Ignores unmapped properties on specific map
});

// or add  inside a profile
public class MyProfile : Profile
{
   this.IgnoreUnmapped();
   CreateMap<MyType1, MyType2>();
}

Implementation:

public static class MapperExtensions
{
    private static void IgnoreUnmappedProperties(TypeMap map, IMappingExpression expr)
    {
        foreach (string propName in map.GetUnmappedPropertyNames())
        {
            if (map.SourceType.GetProperty(propName) != null)
            {
                expr.ForSourceMember(propName, opt => opt.Ignore());
            }
            if (map.DestinationType.GetProperty(propName) != null)
            {
                expr.ForMember(propName, opt => opt.Ignore());
            }
        }
    }

    public static void IgnoreUnmapped(this IProfileExpression profile)
    {
        profile.ForAllMaps(IgnoreUnmappedProperties);
    }

    public static void IgnoreUnmapped(this IProfileExpression profile, Func<TypeMap, bool> filter)
    {
        profile.ForAllMaps((map, expr) =>
        {
            if (filter(map))
            {
                IgnoreUnmappedProperties(map, expr);
            }
        });
    }

    public static void IgnoreUnmapped(this IProfileExpression profile, Type src, Type dest)
    {
        profile.IgnoreUnmapped((TypeMap map) => map.SourceType == src && map.DestinationType == dest);
    }

    public static void IgnoreUnmapped<TSrc, TDest>(this IProfileExpression profile)
    {
        profile.IgnoreUnmapped(typeof(TSrc), typeof(TDest));
    }
}
dampee
  • 3,392
  • 1
  • 21
  • 37
Richard
  • 29,854
  • 11
  • 77
  • 120
  • 3
    How would you use this in a chained `CreateMap()` expression in a `Profile`? – jmoerdyk Jul 07 '16 at 18:35
  • 2
    Thanks for this. The GetUnmappedPropertyNames method returns all unmapped property names, on both the source and destination, which seems to be break on a reverse map, so I had to make a small change to IgnoreUnmapped to check if the unmapped property was on the source or destination and ignore accordingly. Here's a fiddle demonstrating the problem and the update: https://dotnetfiddle.net/vkRGJv – Mun Jul 25 '16 at 21:48
  • 1
    I've updated my answer to include your findings - I don't use Source mappings so hadn't come across this! Thanks. – Richard Jul 26 '16 at 11:48
  • 1
    This doesn't work on PCL without reflection available, GetProperty(propName) doesn't exist. – George Taskos Oct 01 '16 at 23:22
  • I don't see how this is a solution to the question, or how this even does anything. Unmapped properties are already going to be ignored - because they are *unmapped*. The poster said "how do you ignore props unless they are *explicitly* mapped". That means that if I have Src.MyProp and Dest.MyProp, that mapping should be ignored unless there was an explicit call to MapFrom & ForMember for MyProp. So, the default mapping needs to be ignored. The only thing this solution does is to cause the config-valid-assert thing to pass - which you don't need anyway for the mapping to work. – N73k Jun 02 '17 at 03:03
  • Hi Richard, thanks for the answer it guided me on the correct solution for my scenario. I had to make a small tweak to IgnoreUnmappedProperties to do a GetField check as well. I had to mapped a new class using properties to a legacy class that was using fields and the GetProperty checks were not picking them up. This is the fiddle with the changes and test case [link]https://dotnetfiddle.net/WOj7MF – seetdev Sep 22 '17 at 09:43
18

For Automapper 5.0 in order to skip all unmapped properties you just need put

.ForAllOtherMembers(x=>x.Ignore());

at the end of your profile.

For example:

internal class AccountInfoEntityToAccountDtoProfile : Profile
{
    public AccountInfoEntityToAccountDtoProfile()
    {
        CreateMap<AccountInfoEntity, AccountDto>()
           .ForMember(d => d.Id, e => e.MapFrom(s => s.BankAcctInfo.BankAcctFrom.AcctId))
           .ForAllOtherMembers(x=>x.Ignore());
    }
}

In this case only Id field for output object will be resolved all other will be skipped. Works like a charm, seems we don't need any tricky extensions anymore!

framerelay
  • 526
  • 4
  • 5
  • does this really work? using this approach still I get all the other members and set to default... not original values, even using the x=>x.UseDestinationValue() – juagicre Mar 30 '21 at 11:06
17

There's been a few years since the question has been asked, but this extension method seems cleaner to me, using current version of AutoMapper (3.2.1):

public static IMappingExpression<TSource, TDestination> IgnoreUnmappedProperties<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var typeMap = Mapper.FindTypeMapFor<TSource, TDestination>();
    if (typeMap != null)
    {
        foreach (var unmappedPropertyName in typeMap.GetUnmappedPropertyNames())
        {
            expression.ForMember(unmappedPropertyName, opt => opt.Ignore());
        }
    }

    return expression;
}
Iravanchi
  • 5,139
  • 9
  • 40
  • 56
16

For those who are using the non-static API in version 4.2.0 and above, the following extension method (found here in the AutoMapperExtensions class) can be used:

// from http://stackoverflow.com/questions/954480/automapper-ignore-the-rest/6474397#6474397
public static IMappingExpression IgnoreAllNonExisting(this IMappingExpression expression)
{
    foreach(var property in expression.TypeMap.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}

The important thing here is that once the static API is removed, code such as Mapper.FindTypeMapFor will no longer work, hence the use of the expression.TypeMap field.

nick_w
  • 14,758
  • 3
  • 51
  • 71
  • 8
    As of 5.0, `expression.TypeMap` is no longer available. Here's [my solution for 5.0](http://stackoverflow.com/a/38073718/163495) – Richard Jun 28 '16 at 10:31
  • I had to use `public static IMappingExpression IgnoreAllNonExisting(this IMappingExpression expression)` to fix type issues. – Nick M Jun 26 '18 at 04:14
10

I have updated Robert Schroeder's answer for AutoMapper 4.2. With non-static mapper configurations, we can't use Mapper.GetAllTypeMaps(), but the expression has a reference to the required TypeMap:

public static IMappingExpression<TSource, TDestination> 
    IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    foreach (var property in expression.TypeMap.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    return expression;
}
mrmashal
  • 1,721
  • 18
  • 21
  • Doesn't work in AutoMapper 5.0. The .TypeMap property on IMappingExpression is not available. For 5.+ version see extensions in [Richard's answer](http://stackoverflow.com/questions/954480/automapper-ignore-the-rest/38073718#38073718) – Michael Freidgeim Jul 17 '16 at 13:21
  • Works with AM 4.2 – Leszek P Jul 31 '18 at 13:49
7

This seems an old question but thought I would post my answer for anyone else looking like I was.

I use ConstructUsing, object initializer coupled with ForAllMembers ignore e.g

    Mapper.CreateMap<Source, Target>()
        .ConstructUsing(
            f =>
                new Target
                    {
                        PropVal1 = f.PropVal1,
                        PropObj2 = Map<PropObj2Class>(f.PropObj2),
                        PropVal4 = f.PropVal4
                    })
        .ForAllMembers(a => a.Ignore());
gm1886
  • 81
  • 1
  • 2
5

By default, AutoMapper uses the destination type to validate members but you can skip validation by using MemberList.None option.

var configuration = new MapperConfiguration(cfg =>
  cfg.CreateMap<Source2, Destination2>(MemberList.None);
);

You can find the reference here

4

In a WebApi for dotnet 5, using the Nuget package AutoMapper.Extensions.Microsoft.DependencyInjection, I'm doing it like this in a mapper profile. I'm really rusty with AutoMapper, but it seems to work fine now for unmapped members.

In Startup:

var mapperConfig = new MapperConfiguration(mc => mc.AddProfile(new AutoMapperProfile()));
    services.AddSingleton(mapperConfig.CreateMapper());

and in my AutoMapperProfile:

CreateMap<ProjectActivity, Activity>()
        .ForMember(dest => dest.ActivityName, opt => opt.MapFrom(src => src.Name))
        .ValidateMemberList(MemberList.None);
Johan Danforth
  • 4,469
  • 6
  • 37
  • 36
1

I know this is an old question, but @jmoerdyk in your question:

How would you use this in a chained CreateMap() expression in a Profile?

you can use this answer like this inside the Profile ctor

this.IgnoreUnmapped();
CreateMap<TSource, Tdestination>(MemberList.Destination)
.ForMember(dest => dest.SomeProp, opt => opt.MapFrom(src => src.OtherProp));
Community
  • 1
  • 1
j.loucao.silva
  • 321
  • 2
  • 5
1

The only infromation about ignoring many of members is this thread - http://groups.google.com/group/automapper-users/browse_thread/thread/9928ce9f2ffa641f . I think you can use the trick used in ProvidingCommonBaseClassConfiguration to ignore common properties for similar classes.
And there is no information about the "Ignore the rest" functionality. I've looked at the code before and it seems to me that will be very and very hard to add such functionality. Also you can try to use some attribute and mark with it ignored properties and add some generic/common code to ignore all marked properties.

zihotki
  • 5,201
  • 22
  • 26
  • 1
    Perhaps one way would be to use ForAllMembers method and implement my own IMemberConfigurationExpression which receives a string containing the property names of those properties which should not be ignored, and then go through the rest of them and call Ignore(). Just an idea, I'm not sure if it would work. – Igor Brejc Jun 05 '09 at 10:40
  • Yes, this can work too, but this method is more tricky than using attributes but it offers more flexibility. It's a pity that there are no silver bullet :(. – zihotki Jun 05 '09 at 14:00
0

You can use ForAllMembers, than overwrite only needed like this

public static IMappingExpression<TSource, TDest> IgnoreAll<TSource, TDest>(this IMappingExpression<TSource, TDest> expression)
        {
            expression.ForAllMembers(opt => opt.Ignore());
            return expression;
        }

Be carefull, it will ignore all, and if you will not add custom mapping, they are already ignore and will not work

also, i want to say, if you have unit test for AutoMapper. And you test that all models with all properties mapped correctly you shouldn't use such extension method

you should write ignore's explicitly

Anatoli Klamer
  • 2,279
  • 2
  • 17
  • 22
0

If we only want to map the properties of the source object, we can use the following overload of the map method:

DestSampleObjetc dest = new();    
dest = mapper.Map(source, dest);
GPManuel
  • 1
  • 2
-1

I made small improvement. Here is the code:

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>

        (this IMappingExpression<TSource, TDestination> expression)

    {

        var flags = BindingFlags.Public | BindingFlags.Instance;

        var sourceType = typeof(TSource);

        var destinationProperties = typeof(TDestination).GetProperties(flags);



        var memberConfigurations = expression.GetType()

            .GetProperty("MemberConfigurations",

                BindingFlags.NonPublic | BindingFlags.Instance)

            ?.GetValue(expression) as List<IPropertyMapConfiguration>;

        var mappedProperties = memberConfigurations?

            .Select(p => p.DestinationMember.Name)

            .ToList();

        foreach (var property in destinationProperties)

        {

           

            if (mappedProperties != null && mappedProperties.Contains(property.Name))

                continue;

            expression.ForMember(property.Name, opt => opt.Ignore());

        }

        return expression;

    }
Kamyar Miremadi
  • 169
  • 2
  • 7