How to skip the mapping between properties of a source and a target object in Automapper

As I did in my previous article, I focus again on the Automapper framework.

When I map one object to another, I often deal with a target object that contains less properties than the source object. If I take no action, an exception is going to be thrown. For that we will have to declare the skipped properties by using the DoNotValidate method when we define the mapping (CreateMap) between the two objects.

The code is straightforward:

    CreateMap<SourceModel, TargetModel>().ForSourceMember(sourceObj => sourceObj.Description , config => config.DoNotValidate());

In the case where the target object contains more properties than the source object, we can use the Ignore method:

    CreateMap<SourceModel, TargetModel>().ForMember(targetObj => targetObj.Description , config => config.Ignore());

I hope this is going to help some of you, since chances are you will have to deal with mapping of almost identical objects.

comments powered by Disqus