mattruma
mattruma

Reputation: 16677

How can I create a more generic Resolver for Automapper?

For certain properties, when the value is 0, I want to convert the value to NULL.

When I create my map I use a custom resolver to handle the conversion for me, which looks like:

AutoMapper.Mapper.CreateMap<ContactData, Contact>()
     .ForMember(x => x.ContactTypeId, y => y.ResolveUsing<ContactTypeIdZeroToNullResolver>());

And my resolver looks like:

using AutoMapper;

namespace MyCompany.MyProduct.Customers.Data.Helpers
{
    public class ContactTypeIdZeroToNullResolver : ValueResolver<ContactData, int?>
    {
        protected override int? ResolveCore(ContactData source)
        {
            if (source.ContactTypeId == 0)
                return null;

            return source.ContactTypeId;
        }
    }
}

This works just fine!

My question is, is it possible to make this more generic? I tried replace ContactData with just int, but errors keep being thrown.

Upvotes: 2

Views: 572

Answers (1)

Mightymuke
Mightymuke

Reputation: 5144

How about something like this:

AutoMapper.Mapper.CreateMap<int, int?>()
    .ConvertUsing(src => src == 0 ? (int?)null : src);

AutoMapper.Mapper.CreateMap<ContactData, Contact>();

AutoMapper.Mapper.AssertConfigurationIsValid();

(assuming of course that ContactTypeId is an int in ContactData and an int? in Contact)

You should be careful with this as it will apply to ALL your mappings for these types.

You can also inline it like this:

AutoMapper.Mapper.CreateMap<ContactData, Contact>()
    .ForMember(dest => dest.ContactTypeId,
                       opt => opt.MapFrom(src => src.ContactTypeId == 0
                            ? (int?)null
                            : src.ContactTypeId));

which will achieve the same thing, but wont be as generic.

Upvotes: 1

Related Questions