Ignoring Mapping of Unmapped Properties with Automapper
When mapping between two classes using Automapper, it's possible to encounter scenarios where one or more properties in the source class are not present in the destination class. This can lead to exceptions during the mapping process.
Consider the following example:
class OrderModel { public string ProductName; } class Orders { } CreateMap<OrderModel, Orders>();
In this case, attempting to map the OrderModel to the Orders class will result in an exception indicating that the property ProductName on OrderModel is not mapped. To resolve this issue and prevent Automapper from attempting to map unmapped properties, you can use the ForMember method in combination with Ignore.
CreateMap<OrderModel, Orders>() .ForMember(x => x.ProductName, opt => opt.Ignore());
By specifying Ignore as an option, Automapper will skip the mapping of the ProductName property. This allows the mapping process to proceed without encountering any exceptions.
Updated: DoNotValidate Instead of Ignore
In AutoMapper 8.0, the Ignore option has been replaced with DoNotValidate. Therefore, the code snippet above should be updated as follows:
CreateMap<OrderModel, Orders>() .ForMember(x => x.ProductName, opt => opt.DoNotValidate());
The above is the detailed content of How to Ignore Unmapped Properties in AutoMapper?. For more information, please follow other related articles on the PHP Chinese website!