Home > Backend Development > C++ > How to Ignore Unmapped Properties in AutoMapper?

How to Ignore Unmapped Properties in AutoMapper?

Barbara Streisand
Release: 2025-01-03 18:39:41
Original
466 people have browsed it

How to Ignore Unmapped Properties in AutoMapper?

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>();
Copy after login

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());
Copy after login

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());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template