System.Reflection.TargetInvocationException: "Expression 'dest => dest' must resolve to top-level member" when configuring AutoMapper profile
Julia Ohorodnichuk
0
Reputation points
I'm encountering an exception when trying to configure AutoMapper in my ASP.NET Core application. The exception message is:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: Expression 'dest => dest' must resolve to top-level member and not any child object's properties. You can use ForPath, a custom resolver on the child type or the AfterMap option instead. (Parameter 'lambdaExpression') at AutoMapper.Internal.ReflectionHelper.FindProperty(LambdaExpression lambdaExpression)
Here is my AutoMapper profile configuration:
public class AuthenticationMappingProfile : Profile
{
public AuthenticationMappingProfile()
{
CreateMap<(RegisterRequest registerRequest, string BaseUrl, byte[] Image), RegisterCommand>()
.ForPath(dest => dest.BaseUrl, opt => opt.MapFrom(src => src.BaseUrl))
.ForPath(dest => dest.Avatar, opt => opt.MapFrom(src => src.Image))
.ForPath(dest => dest.FirstName, opt => opt.MapFrom(src => src.registerRequest.FirstName))
.ForPath(dest => dest.LastName, opt => opt.MapFrom(src => src.registerRequest.LastName))
.ForPath(dest => dest.Email, opt => opt.MapFrom(src => src.registerRequest.Email))
.ForPath(dest => dest.Password, opt => opt.MapFrom(src => src.registerRequest.Password))
.ForPath(dest => dest.ConfirmPassword, opt => opt.MapFrom(src => src.registerRequest.ConfirmPassword))
.ForPath(dest => dest.Birthday, opt => opt.MapFrom(src => src.registerRequest.Birthday))
.ForPath(dest => dest.Gender, opt => opt.MapFrom(src => src.registerRequest.Gender))
.ForPath(dest => dest.Avatar, opt => opt.MapFrom(src => src.Image));
}
}
Here are the related classes:
public record RegisterRequest
{
public string FirstName { get; init; }
public string LastName { get; init; }
public string Email { get; init; }
public string Password { get; init; }
public string ConfirmPassword { get; init; }
public DateTime Birthday { get; init; }
public string Gender { get; init; }
public IFormFile? Avatar { get; init; }
}
public record RegisterCommand(
string FirstName,
string LastName,
string Email,
string Password,
string ConfirmPassword,
DateTime Birthday,
string Gender,
byte[]? Avatar,
string BaseUrl
) : IRequest<ErrorOr<AuthenticationResult>>;
The exception is thrown during the AutoMapper profile creation. The goal is to map from a tuple (RegisterRequest registerRequest, string BaseUrl, byte[] Image) to RegisterCommand
What I have tried:
Verified the property names and types in the destination and source classes. Checked the AutoMapper documentation for mapping complex types and used .ForPath, ForCtorParam and .ForMember
Sign in to answer