简体   繁体   中英

Problem with mapping objects with automapper

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.

在此处输入图片说明 在此处输入图片说明

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: List 1 -> PostForReturnDto System.Collections.Generic.List 1[[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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM