C#C
C#2y ago
kurumi

✅ AutoMapper record to class problems

I need to create map from
public record MessageModel(
    int MessageId,
    int AuthorId,
    string Text,
    IEnumerable<int> Likes,
    DateTime SendDate);

to:
public class MessageEntity
{
    public int Id { get; set; }
    public int AuthorId { get; set; }
    public UserEntity? Author { get; set; }
    public string Text { get; set; } = string.Empty;
    public DateTime SendDate { get; set; }
    public List<MessageLikeEntity> Likes { get; set; } = new List<MessageLikeEntity>();
}


I quickly made it:
CreateMap<MessageModel, MessageEntity>()
    .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.MessageId));

So I want keep Id, AuthorId, Text and SendDate be mapped

But it throws exception:
AutoMapper.AutoMapperMappingException
Message=Error mapping types.
Source=AutoMapper
Inner Exception 1:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.

So what I did wrong?
Surprising, this maps fine:
public record UserModel(
    int UserId,
    string Name,
    UserGender Gender,
    DateTime DateOfBirth,
    DateTime LastVisit,
    bool Online);

public class UserEntity
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public UserGender Gender { get; set; }
    public DateTime DateOfBirth { get; set; }
    public DateTime LastVisit { get; set; }
    public bool Online { get; set; }
    public List<FriendRequestEntity> SendFriendRequests { get; set; } = new List<FriendRequestEntity>();
    public List<FriendRequestEntity> ReceivedFriendRequests { get; set; } = new List<FriendRequestEntity>();
    public List<MessageEntity> Messages { get; set; } = new List<MessageEntity>();
    public List<MessageLikeEntity> MessageLikes { get; set; } = new List<MessageLikeEntity>();
}

CreateMap<UserModel, UserEntity>()
    .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.UserId));
Was this page helpful?