Automapper:忽略目标的验证异常 属性

Automapper: validation exception ignoring destination property

我在尝试忽略目的地时遇到问题 属性

来源class:

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

目的地class:

public class ClassModel
{

    public int Id { get; set; }

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

}

示例:

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

    }
}

很遗憾config.AssertConfigurationIsValid();出现异常:

$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

我无法理解为什么,我明确表示要通过 DoNotUseDestinationValue 忽略 ListString

提前致谢

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.

所以尝试使用这个:

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