Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper - Ignore mapping with condition

I'm using automapper and I would like to know if it's possible to ignore a mapping of a field when that's null.

That's my code:

.ForMember(dest => dest.BusinessGroup_Id, 
           opt => opt.MapFrom(src => (int)src.BusinessGroup))
  • src.BusinessGroup type = "enum"
  • dest.BusinessGroup_Id = int

The objective it's to ingore that Mapping if src.BusinessGroup = null.

like image 250
user1520494 Avatar asked Nov 02 '12 11:11

user1520494


People also ask

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

What is conditional mapping?

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.

Is it good to use AutoMapper?

AutoMapper is a great tool when used for simple conversions. When you start using more complex conversions, AutoMapper can be invaluable. For very simple conversions you could of course write your own conversion method, but why write something that somebody already has written?


1 Answers

I think NullSubstitute option will do the trick

.ForMember(d => d.BusinessGroup_Id, o => o.MapFrom(s => (int?)s.BusinessGroup));
.ForMember(d => d.BusinessGroup_Id, o => o.NullSubstitute(0));

BTW you can write your conditions in mapping action:

.ForMember(d => d.BusinessGroup_Id,
           o => o.MapFrom(s => s.BusinessGroup == null ? 0 : (int)s.BusinessGroup));   

UPDATE if you cannot assign some default value to your property, you can just ignore it and map only not nulls:

.ForMember(d => d.BusinessGroup_Id, o => o.Ignore())
.AfterMap((s, d) =>
    {
        if (s.BusinessGroup != null)
            d.BusinessGroup_Id = (int)s.BusinessGroup;
    });
like image 189
Sergey Berezovskiy Avatar answered Oct 22 '22 04:10

Sergey Berezovskiy