Home > Net >  Automapper: validation exception ignoring destination property
Automapper: validation exception ignoring destination property

Time:11-12

I have troubles trying to ignore a destination property

Source class:

public class ClassDto
{
    public int Id { get; set; }
}

Destination class:

public class ClassModel
{

    public int Id { get; set; }

    public IList<string> ListString { get; set; }

}

Example:

public class Program
{
    static void Main(string[] args)
    {
        var dto = new ClassDto { Id = 1 };

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<ClassDto, ClassModel>().
            ForMember(i => i.ListString, opt => opt.DoNotUseDestinationValue()); 
        });

        config.AssertConfigurationIsValid();

        var mapper = config.CreateMapper();

        var model = mapper.Map<ClassDto, ClassModel>(dto);

    }
}

Unfortunately config.AssertConfigurationIsValid(); rises an exception:

$exception {"\nUnmapped members were found. Review the types and members below.\nAdd a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type\nFor no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters\n===================================================\r\nClassDto -> ClassModel (Destination member list)\r\nAutoMapperFoo.ClassDto -> AutoMapperFoo.ClassModel (Destination member list)\r\n\r\nUnmapped properties:\r\nListString\r\n"} AutoMapper.AutoMapperConfigurationException

I can't undesrtand why, I explicit to ignore ListString by DoNotUseDestinationValue

Thanks in advance

CodePudding user response:

By default, AutoMapper tries to map all the properties from the source type to the destination type when both source and destination type property names are the same. If you want some of the properties not to map with the destination type property then you need to use the AutoMapper Ignore Property in C#. Learn more AutoMapper Ignore Property in C#

Automapper gives the property Ignore which tells the mapper to not take the value of a property from the source class. Ignore not only ignore the mapping for the property, but also ignore the mapping of all inner properties. It means that if the property is not a primitive type, but another class, that if you are using Ignore, this class properties won't be mapped. So, A.B.C would be A.Null.

So try using this:

.ForMember(x => x.ListString, opt => opt.Ignore())
  • Related