AutoMapper: "Ignore the rest"?
Asked Answered
G

19

245

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.

Glia answered 5/6, 2009 at 6:18 Comment(6)
with the ValueInjecter 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 propertiesSaltworks
For those using Automapper > version 5, skip down to see answers detailing .ForAllOtherMembers(opts => opts.Ignore())Catechism
@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.Eckart
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.Flatware
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.Aqualung
The solution for AutoMapper 11 is #72367821Wingover
D
89

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.

Dreyfus answered 8/6, 2011 at 14:44 Comment(8)
I haven't used AutoMapper for some time, but I'll accept your answer if it works for you :).Glia
Thanks!! I found this very handy. Ignoring properties individually was defeating the purpose of using automapper in my situation.Inferno
See the next answer for one that doesnt have the overwrite problemCarvalho
This method should be on the autoMapper native code! Very nice, thank you!Dissimilation
FYI, Jimmy himself (writer of AutoMapper) has commented below that @nazim's answer is correct for version 5+Nawab
Works fine in Version 8.0.Crude
@JasonCoyne , ten years later and SO has implemented dynamic sorting of the answers. Do you remember which answer were "the next one"? 🙂Cableway
Thank you alot for simple trick to ignore unmapped fieldsUrsola
S
339

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);  
Sashenka answered 2/7, 2015 at 10:43 Comment(16)
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.Ynes
It won't work if you want to ignore few properties on both source and destination :)Cinematograph
@KManohar why would you want to ignore on both the source and destination? AutoMapper only validates one side or the other.Shoreline
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?Labaw
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.Vudimir
To anyone that comes later, THIS IS THE CORRECT ANSWER FOR 5.0Shoreline
The question is for AutoMapper 2.0. This does work for 5.0, but does it apply to the original question?Louvain
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.Gignac
looks nifty but did not work for me.. i tried Source and Destination, but it keeps complaining about the same property object missing a mapMerilee
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"Newtonnext
Works, but I think you have the order of source and destination reversed in your examples?Vulpecula
In case you need to ignore extra properties .ForSourceMember(src => src.Name, opt => opt.Ignore());Mccourt
FWIW in @Mccourt 's code I had to use DoNotValidate instead of IgnoreMasaryk
This should be marked as correct answer as this infers the best practices using AutoMapper!Youngyoungblood
Even ChatGPT 4.0 couldn't figure this one out. Glad I came across this answer.Mchale
This doesn't work for me. My Source and Destination have some properties with different names.Jocular
B
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

Betray answered 24/6, 2011 at 22:27 Comment(13)
+1, Thanks to you for posting this solution. It tooked me hours for figuring weird bug when I use solution in goo.gl/rG7SL, until I stumble to this post again.Urbannai
makes sense, seems like a more robust solution, updated my answer to point to yours. did not know of a method "GetUnmappedPropertyNames" :)Dreyfus
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.Bruce
I recommend Yohanb's method below over this. There are some corner cases that this doesn't work for it appears.Mensa
@Urbannai 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?Superposition
@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.Urbannai
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.Focalize
Can this be done in AutoMapper 4.2? (The Mapper.GetAllTypeMaps() is deprecated)Authorized
@Authorized The AutoMapper 4.2 approach is described in this answer.Internationale
For AutoMapper 5+ version just replace Mapper.GetAllTypeMaps() with Mapper.Configuration.GetAllTypeMaps(). Here is the reference github.com/AutoMapper/AutoMapper/issues/1252Erythema
@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."Rieth
@HiralDesai this will not work for the ProjectTo() I guess. But it's out of the scope of the questionErythema
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. github.com/AutoMapper/AutoMapper/issues/1839 So example: https://mcmap.net/q/116193/-automapper-quot-ignore-the-rest-quotUterine
F
106

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.

Fideliafidelio answered 23/8, 2016 at 20:58 Comment(8)
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?Catechism
Thank you for this, took me awhile to scroll down to it but this, but it works perfectly.Travistravus
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.Flatware
This is now the preferred approach. Wonder if the OP could change the accepted answer?Norahnorbert
Is there an equivalent to ignore the properties in the source object? Something like ForAllOtherSourceMembers?Capitalism
@Capitalism there is MemberList enum, just place it in a CreateMap method as param like this: CreateMap<Source, Destination>(MemberList.Source)Chronometry
Even it answers the question, Jimmy Bogard explained that ForAllOtherMembers(opts => opts.Ignore()) defeats the purpose of Automapper. Consider to use IgnoreUnmapped<Src, Dest>()to still have members mapped by convention and just avoid alert from AssertConfigurationIsValid()Wingover
ForAllOtherMembers extension method was removed from Automapper 11. If you still need it, see #71311803Wingover
D
89

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.

Dreyfus answered 8/6, 2011 at 14:44 Comment(8)
I haven't used AutoMapper for some time, but I'll accept your answer if it works for you :).Glia
Thanks!! I found this very handy. Ignoring properties individually was defeating the purpose of using automapper in my situation.Inferno
See the next answer for one that doesnt have the overwrite problemCarvalho
This method should be on the autoMapper native code! Very nice, thank you!Dissimilation
FYI, Jimmy himself (writer of AutoMapper) has commented below that @nazim's answer is correct for version 5+Nawab
Works fine in Version 8.0.Crude
@JasonCoyne , ten years later and SO has implemented dynamic sorting of the answers. Do you remember which answer were "the next one"? 🙂Cableway
Thank you alot for simple trick to ignore unmapped fieldsUrsola
J
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.

Jeddy answered 8/12, 2011 at 15:50 Comment(2)
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.Tachygraphy
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?Newtonnext
R
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));
    }
}
Rothstein answered 28/6, 2016 at 10:30 Comment(6)
How would you use this in a chained CreateMap<TSource,TDest>() expression in a Profile?Berberidaceous
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: dotnetfiddle.net/vkRGJvGood
I've updated my answer to include your findings - I don't use Source mappings so hadn't come across this! Thanks.Rothstein
This doesn't work on PCL without reflection available, GetProperty(propName) doesn't exist.Bald
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.Flatware
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]dotnetfiddle.net/WOj7MFAmplify
M
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!

Misappropriate answered 25/8, 2016 at 11:41 Comment(1)
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()Stasiastasis
M
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;
}
Muncey answered 5/11, 2014 at 15:8 Comment(0)
L
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 https://mcmap.net/q/116193/-automapper-quot-ignore-the-rest-quot/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.

Llovera answered 29/1, 2016 at 7:5 Comment(2)
As of 5.0, expression.TypeMap is no longer available. Here's my solution for 5.0Rothstein
I had to use public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression) to fix type issues.Elderberry
A
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;
}
Authorized answered 13/2, 2016 at 5:54 Comment(2)
Doesn't work in AutoMapper 5.0. The .TypeMap property on IMappingExpression is not available. For 5.+ version see extensions in Richard's answerWingover
Works with AM 4.2Treillage
H
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());
Harken answered 7/3, 2014 at 22:33 Comment(0)
D
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

Devilkin answered 2/2, 2021 at 3:27 Comment(0)
A
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);
Alveolus answered 17/3, 2021 at 17:2 Comment(1)
I wonder what the difference is between .ValidateMemberList(MemberList.None) and .ForAllOtherMembers(x => x.Ignore())?Defy
Q
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.

Quoit answered 5/6, 2009 at 10:27 Comment(2)
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.Glia
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 :(.Quoit
Z
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));
Zebu answered 22/3, 2017 at 10:33 Comment(0)
M
1

Normally you won't need this. I had a temporary configuration and I used this:

 cfg.ShouldMapProperty = p => false;

Then all explicit mappings worked fine. Automapper 12+

Mayo answered 28/10, 2023 at 13:12 Comment(0)
P
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

Potoroo answered 29/7, 2016 at 9:34 Comment(0)
C
0

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;

    }
Cartesian answered 25/4, 2023 at 21:44 Comment(0)
K
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);
Krick answered 16/8, 2023 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.