1
votes

I have a problem with mapping. Here is my model.

    public class Post
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public DateTime Created { get; set; }
        public User User { get; set; }
        public int UserId { get; set; }
    }

My Dto:

public class PostForReturnDto
    {
        public PostForReturnDto()
        {
             Created = DateTime.Now;
        }
         public int Id { get; set; }
        public string Description { get; set; }
        public DateTime Created { get; set; }
        public string Author { get; set; }
    }

AutoMapperProfiles.cs

 CreateMap<Post, PostForReturnDto>()
            .ForMember(p => p.Author,
             opt => opt.MapFrom(src => src.User.KnownAs));

RepositoryContext

 public async Task<IEnumerable<Post>> GetPosts() {
             var posts = _context.Posts
            .Include(u => u.User)
            .OrderByDescending(p => p.Created)
            .ToListAsync();

            return await posts;
        }

While in debug mode in the PostController I receive the following information with the user object inside.

enter image description here enter image description here

I'm trying to map KnownAs property from the User object to my DTO, but with no success. The error is:

AutoMapper.AutoMapperMappingException: Missing type map configuration or unsupported mapping. Mapping types: List1 -> PostForReturnDto System.Collections.Generic.List1[[DateApp.API.Models.Post, DateApp.API, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> DateApp.API.Dtos.PostForReturnDto at lambda_method(Closure , List`1 , PostForReturnDto , ResolutionContext ) at lambda_method(Closure , Object , Object , ResolutionContext ) at AutoMapper.Mapper.Map[TDestination](Object source) in C:\projects\automapper\src\AutoMapper\Mapper.cs:line 35

1
Does this answer your question? Mapping collections using AutoMapperoleksa

1 Answers

2
votes

Seems that you are mapping the List<Post> not the Post instance like it should be

try like below

var posts = await _repo.GetPosts();

var res = posts.Select(_ => _mapper.Map<PostToReturn>(_));

return Ok(res);

or you can map the collection having generic argument as documentation says

IEnumerable<PostToReturn> postToReturn= mapper.Map<IEnumerable<Post>, IEnumerable<PostToReturn>>(posts);

UPD Seems your GetPosts() implementation lacks some Where or Take filter. It takes all posts right now and it can cause performance problem in the production if there are a lot of posts.