Is it possible to ignore mapping a member depending on the value of a source property?
For example if we have:
public class Car { public int Id { get; set; } public string Code { get; set; } } public class CarViewModel { public int Id { get; set; } public string Code { get; set; } }
I'm looking for something like
Mapper.CreateMap<CarViewModel, Car>() .ForMember(dest => dest.Code, opt => opt.Ignore().If(source => source.Id == 0))
So far the only solution I have is too use two different view models and create different mappings for each one.
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.
AutoMapper in C# is a library used to map data from one object to another. It acts as a mapper between two objects and transforms one object type into another. It converts the input object of one type to the output object of another type until the latter type follows or maintains the conventions of AutoMapper.
Conditional Field Mapping allows you to control whether or not a value or field is written to a target datastore based on the contents of the source data. For example, if there is a NULL value in a source field, you can choose to overwrite target data with the NULL value or skip that field when updating a record.
Open startup. cs class file, add “services. AddAutoMapper(typeof(Startup))” in configure services method. Now the AutoMapper Package was installed and configured in our project.
The Ignore() feature is strictly for members you never map, as these members are also skipped in configuration validation. I checked a couple of options, but it doesn't look like things like a custom value resolver will do the trick.
Use the Condition() feature to map the member when the condition is true:
Mapper.CreateMap<CarViewModel, Car>() .ForMember(dest => dest.Code, opt => opt.Condition(source => source.Id != 0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With