DEV Community

Cesar Aguirre
Cesar Aguirre

Posted on β€’ Originally published at canro91.github.io

1 1 1

TIL: AutoMapper Only Considers Simple Mappings When Validating Configurations

I originally posted this post on my blog.


Oh boy! AutoMapper once again.

Today I have CreateMovieRequest with a boolean property ICanWatchItWithKids that I want to map to a MPA rating. You know G, PG, PG-13...those ones.

If I can watch it with kids, the property MPARating on the destination type should get "General." Anything else gets "Restricted."

To my surprise, this test fails:

using AutoMapper;

namespace TestProject1;

[TestClass]
public class WhyAutoMapperWhy
{
    public class CreateMovieRequest
    {
        public string Name { get; set; }
        public bool ICanWatchItWithKids { get; set; }
    }

    public class Movie
    {
        public string Name { get; set;}
        public MPARating Rating { get; set;}
    }

    public enum MPARating
    {
        // Sure, there are more.
        // But these two are enough.
        General,
        Restricted
    }

    [TestMethod]
    public void AutoMapperConfig_IsValid()
    {
        var mapperConfig = new MapperConfiguration(options =>
        {
            options.CreateMap<CreateMovieRequest, Movie>(MemberList.Source)
                    .ForMember(
                        dest => dest.Rating,
                        opt => opt.MapFrom(src => src.ICanWatchItWithKids
                                                        ? MPARating.General
                                                        : MPARating.Restricted));
        });

        mapperConfig.AssertConfigurationIsValid();
        //           πŸ‘†πŸ‘†πŸ‘†                                                       
        // AutoMapper.AutoMapperConfigurationException:
        // CreateMovieRequest -> Movie (Source member list)
        // TestProject1.WhyAutoMapperWhy+CreateMovieRequest -> TestProject1.WhyAutoMapperWhy+Movie (Source member list)
        //
        // Unmapped properties:
        // ICanWatchItWithKids
    }
}
Enter fullscreen mode Exit fullscreen mode

It turns out that starting from AutoMapper version 10.0, only source members expressions are considered when validating mappings. And it's buried in the Upgrade Guide here. Arrggg!

Two solutions: One for the lazy and the right one

Since I'm validating mappings based on the source type, I can simply ignore it:

options.CreateMap<CreateMovieRequest, Movie>(MemberList.Source)
    .ForMember(
        dest => dest.Rating,
        opt => opt.MapFrom(src => src.ICanWatchItWithKids ? MPARating.General : MPARating.Restricted))
    .ForSourceMember(src => src.ICanWatchItWithKids, opt => opt.DoNotValidate());
    // πŸ‘†πŸ‘†πŸ‘†
    // Thanks AutoMapper, I'll take it from here.
Enter fullscreen mode Exit fullscreen mode

It feels like cheating, but it works.

Or, I can use a converter:

options.CreateMap<CreateMovieRequest, Movie>(MemberList.Source)
    .ForMember(
        dest => dest.Rating,
        opt => opt.ConvertUsing( // πŸ‘ˆ
                new FromBoolToMPARating(), // πŸ‘ˆ
                src => src.ICanWatchItWithKids));

// And here's the converter: πŸ‘‡
public class FromBoolToMPARating : IValueConverter<bool, MPARating>
{
    public MPARating Convert(bool sourceMember, ResolutionContext context)
    {
        // Here's the actual mapping: πŸ‘‡      
        return sourceMember ? MPARating.General : MPARating.Restricted;
    }
}
Enter fullscreen mode Exit fullscreen mode

Another day working with AutoMapper. It would have been way easier mapping that by hand.


Join my email list and get a short, 2-minute email with 4 curated links about programming and software engineering delivered to your inbox every Friday.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Image of DataStax

Langflow: Simplify AI Agent Building

Langflow is the easiest way to build and deploy AI-powered agents. Try it out for yourself and see why.

Get started for free

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay