Reputation: 4224
I have recently started using automapper and it has work fine for me so far. I have been mapping domain objects to corresponding dtos and by default all source properties get mapped to their matching destination properties. I have been using code as follows:
Mapper.CreateMap<Node, NodeDto>();
var nodeDto = Mapper.Map<Node, NodeDto>( node );
Now I have got into a situation where I would like to map only some of the properties of the source object. There are collection properties in the source object that I do not want to be mapped to the matching destination properties. Is there a way to achieve that?
Upvotes: 8
Views: 10637
Reputation: 6400
The marked answer is appropriate if you want to ignore a small set of properties. If you need to map a small set of properties using a TypeConverter might be more appropriate.
// Configure map using TypeConverter
cfg.CreateMap<MySource, MyDestination>()
.ConvertUsing(new MyTypeConverter());
public class MyTypeConverter : ITypeConverter<MySource, MyDestination>
{
public MyTypeConverter() : base()
{
}
public MyDestination Convert(MySource source, MyDestination destination, ResolutionContext context)
{
MyDestination myObj = destination == null ? new MyDestination() : destination;
myObj.Prop1 = source.Prop1;
myObj.Prop2 = source.Prop2;
return myObj;
}
}
Upvotes: 1
Reputation: 1038720
You could specify the properties to ignore like this:
Mapper.CreateMap<Node, NodeDto>()
.ForMember(dest => dest.SomePropToIgnore, opt => opt.Ignore())
Upvotes: 14