1

Our entities have a field called "DateDeleted". At times we might have these loaded into entities and we want to filter them out before sending them to the client.

Our Entities also have child entities which have child entities, all who have a DateDeleted.

What's the best practice to implement this with Automapper - Specifically - how can I map a Null value to the destination (for the entire object) when the source has a Date Deleted property with a value?

1 Answer 1

3

You can ignore a specific property when you configure your mappings

CreateMap<srcType, destType>.ForMember(x => x.DateDeleted, opt => opt.Ignore());

EDIT: To do custom conditional logic during the mapping you will need to implement a custom resolver:

public class NullCheckResolver : IValueResolver<TSrc, TDest, TProp>
{
    public TProp Resolve(TSrc source, TDest destination, TProp member, ResolutionContext context)
    {
        if (member.DateDeleted == null)
            return member;
        return null;
    }
}

CreateMap<TSrc, TDest>().ForMember(dest => dest.MyOptionalProperty, opt => opt.ResolveUsing<NullCheckResolver>());

For more details on custom resolvers, see the AutoMapper documentation

Sign up to request clarification or add additional context in comments.

8 Comments

I don't want to ignore the property, I don't want to map the object if the objects property is a certain value
I see what you are saying, give me a second I'll update my answer
Why would you want to do this using automapper instead of filtering the result set before mapping?
@DavidLibido 1. efficiency - if you filter the result set before hand then you loop over the collection once to filter the values and again to do the mapping, whereas with this route you only loop over the collection once. 2. configuration - if you have a lot of different places that need to perform this mapping (say between a Model and a ViewModel on a bunch of different controllers) then you can configure this in one location and it would apply to all places that perform that mapping. That being said, there is a time and a place for AutoMapper and it needs to be justified.
@RyanTernier apologies - I had a typo. The resolver should return TProp in my example. TProp should be the object type of the property you want to conditionally return null on
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.