AutoMapper "needs to have constructor with 0 args or only optional args" when mapping class to record

Viewed 1324

I have a mapping configuration that defines mapping from an AccessToken database entity to an AccessTokenResponseDto like this:

            CreateMap<AccessToken, AccessTokenResponseDto>()
                .ForMember(dest => dest.ExpiryDate,
                    opt => opt.MapFrom(src => src.ExpiryDate.ToShortDateString("yyyy-MM-dd")))
                .ForMember(dest => dest.Token,
                opt => opt.MapFrom(src => src.Value));

And my AccessToken.cs and AccessTokenResponseDto.cs look like this:

    public class AccessTokens
    {
        public int Id { get; set; }
        public int UserId { get; set; }
        public string FriendlyName { get; set; }
        public DateTime ExpiryDate { get; set; }
        public string Value { get; set; }
    }
       public record AccessTokenResponseDto (int Id, string Token, string ExpiryDate, string FriendlyName);

Then in my application I retrieve all AccessTokens for a user and attempt to map them to the response dto like this:

            var tokens = _dbContext.AccessTokens
                .Where(token => token.UserId == _user.Id)
                .ToList();

            var mappedTokens = _autoMapper.Map<List<AccessTokenResponseDto>>(tokens);

However this gives me the following error:

enter image description here

I am not sure how to approach this problem. Other places in my code I map from a record to another record and this works just fine, so I am not sure if the problem is due to mapping from a class to a record? Or if it has something to do with some of the property names/types not matching, but I would think that the configuration in the CreateMap method would handle this (e.g. mapping from src.Value to dest.Token and formatting ExpiryDate to a string). I also tried using DisableCtorValidation(), but it still gave the same error. Any ideas?

1 Answers
Related