Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper: Ignore on condition of

Tags:

c#

automapper

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.

like image 755
Castrohenge Avatar asked Mar 15 '10 23:03

Castrohenge


People also ask

How to Ignore property in AutoMapper?

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.

How does AutoMapper work in C#?

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.

What is a conditional map?

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.

How do I use Auto Mapper?

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.


1 Answers

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)) 
like image 94
Jimmy Bogard Avatar answered Oct 14 '22 16:10

Jimmy Bogard