Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

automapper - ignore mapping if property type is different with same property name - C#

How can I ignore mapping if property type is different with same property name? By default it's throwing error.

Mapper.CreateMap<EntityAttribute, LeadManagementService.LeadEntityAttribute>();

Model = Mapper.Map<EntityAttribute, LeadManagementService.LeadEntityAttribute>(EntityAttribute);

I know a way to specify the property name to ignore but that's not what I want.

  .ForMember(d=>d.Field, m=>m.Ignore());

Because in the future I might add new properties. So i need to ignore mapping for all properties with different data types.

like image 945
GorvGoyl Avatar asked Jun 28 '16 14:06

GorvGoyl


People also ask

How do I 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.

What is reverse map in AutoMapper?

The Automapper Reverse Mapping is nothing but the two-way mapping which is also called as bidirectional mapping. As of now, the mapping we discussed are one directional means if we have two types let's say Type A and Type B, then we Map Type A with Type B.

What is the use of AutoMapper 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.


1 Answers

You can use ForAllMembers() to setup the appropriate mapping condition:

Mapper.Initialize(cfg =>
{
    cfg.CreateMap<EntityAttribute, LeadEntityAttribute>().ForAllMembers(memberConf =>
    {
        memberConf.Condition((ResolutionContext cond) => cond.DestinationType == cond.SourceType);
    });
}

You can also apply it globally using ForAllMaps():

Mapper.Initialize(cfg =>
{
    // register your maps here
    cfg.CreateMap<A, B>();

    cfg.ForAllMaps((typeMap, mappingExpr) =>
    {
        var ignoredPropMaps = typeMap.GetPropertyMaps();

        foreach (var map in ignoredPropMaps)
        {
            var sourcePropInfo = map.SourceMember as PropertyInfo;
            if (sourcePropInfo == null) continue;

            if (sourcePropInfo.PropertyType != map.DestinationPropertyType)
                map.Ignore();
        }
    });
});
like image 145
haim770 Avatar answered Sep 28 '22 09:09

haim770