Search code examples
c#asp.net.netautomapper

C# AutoMapper "needs to have a constructor with 0 args or only optional args"


It is necessary to convert from this:

public record CreateBulletinRequest(string Text, int Rating, DateTimeOffset Expiry, Guid UserId);

to this:

public record CreateBulletinCommand(string Text, int Rating, DateTime ExpiryUtc, Guid UserId);

I am using this converter params:

public class BulletinMappingProfile : Profile
{
    public BulletinMappingProfile()
    {
        CreateMap<CreateBulletinRequest, CreateBulletinCommand>()
            .ForMember(
                dest => dest.ExpiryUtc,
                opt => opt.MapFrom(src => src.Expiry));

        CreateMap<UpdateBulletinRequest, UpdateBulletinCommand>()
            .ForMember(
                dest => dest.ExpiryUtc,
                opt => opt.MapFrom(src => src.Expiry));
    }
}

But I get this message:

UpdateBulletinCommand needs to have a constructor with 0 args or only optional args. Validate your configuration for details. (Parameter 'type')

I tried to add such code, but without success:

CreateMap<DateTimeOffset, DateTime>().ConvertUsing(src => src.UtcDateTime);

Solution

  • If you have access to the target record you can try adding a constructor with zero parameters (as suggested by the error message) initialising your record properties with default values that might make sense to you, something like this:

    public record CreateBulletinCommand(string Text, int Rating, DateTime ExpiryUtc, Guid UserId)
    {
       public CreateBulletinCommand() :
          this(string.Empty, -1, DateTime.MinValue, Guid.Empty)
    }
    

    Another option that you might explore is replacing ForMember with ForCtorParam as per https://docs.automapper.org/en/stable/Construction.html.