Automapper fails to map nested properties when the logic is separated into a method

50 Views Asked by At

I am using Automapper in a .NET Core 6 project and have an interface IMapFrom that basically creates a map to the profile. Sometimes I have some more complicated mappings, I wanted to have the logic separated in a method, so it is more readable, but when I try to do it, it fails as EF Core doesn't load the nested properties or collections.

Example of working code (very simplified, the real logic has more checks and so on):

class UserDto : IMapFrom<User>
{
    public string Name { get; set; }
    
    public string GrandfatherName { get; set; }

    public void Mapping(Profile profile)
    {
        profile
            .CreateMap<User, UserDto>()
            .ForMember(j => j.GrandfatherName, opt => opt.MapFrom(x => x.Family.Grandfather.Name));
    }
}

And when I try to put the same logic in a method, it doesn't work:

class UserDto : IMapFrom<User>
{
    public string Name { get; set; }
    
    public string GrandfatherName { get; set; }

    public void Mapping(Profile profile)
    {
        profile
            .CreateMap<User, UserDto>()
            .ForMember(j => j.GrandfatherName, opt => opt.MapFrom(x => MapGrandfatherName(x)));
    }

    private static string MapGrandfatherName(User user) {
        return user.Family.Grandfather.Name;
    }

}

I have, of course, tried to call the method with the nested prop like MapGrandfatherName(x.Family.Grandfather) and this works but it loses the point of making the code more readable. Also the error that is thrown is Object reference not set to an instance of an object. which means that even in my code that has if clauses and so on, the mapping doesn't work because of the Family object being null.

Is there any way I can inscruct the automapper to include to proerties when doing the mappings (inside the dto class, I don't want to add includes everywhere where I call the mapping) or I should just accept that passing the exact object that I need is what needs to be done in this case?

0

There are 0 best solutions below