Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper v5 Ignore unmapped properties

Previously when I used Automapper v3.x ignoring unmapped properties could be done by simply adding a .IgnoreUnmappedProperties() extension which looked like this

public static class AutoMapperExtensions
{

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;
    }
}

How can this extension be rewritten to work with Version 5.x. I can of course add the following to each property.

.ForMember(dest => dest.LastUpdatedBy, opt => opt.Ignore())

or not call

Mapper.AssertConfigurationIsValid();
like image 678
MartinS Avatar asked Oct 11 '16 09:10

MartinS


People also ask

How do I ignore properties in AutoMapper?

So, the AutoMapper Ignore() method is used when you want to completely ignore the property in the mapping. The ignored property could be in either the source or the destination object.

How do you ignore fields in Mapper?

We can ignore unmapped properties in several mappers by setting the unmappedTargetPolicy via @MapperConfig to share a setting across several mappers.

Is AutoMapper case sensitive?

The name should be the same but NOT CASE-SENSITIVE i.e. the name in source object can be “id” and that in the target object can be “ID”.

How does AutoMapper work internally?

How AutoMapper works? AutoMapper internally uses a great concept of programming called Reflection. Reflection in C# is used to retrieve metadata on types at runtime. With the help of Reflection, we can dynamically get a type of existing objects and invoke its methods or access its fields and properties.


1 Answers

You can do that using the CreateMap method's memberList parameter to specify the validation that you want.

CreateMap<TSource, TDestination>(MemberList.None)

The MemberList.None should do the trick. You can also switch between the source or destination validations.

Automapper - Selecting members to validate

like image 114
Ahmed IG Avatar answered Sep 20 '22 14:09

Ahmed IG