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.
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.
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.
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.
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();
}
});
});
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