简体   繁体   中英

How do I map Objects in this scenario using c# AutoMapper

This is the Source Object I want to map

 public class Post
{ 
    public string PostId { get; set; }
    public string PostTitle { get; set; } 
    public virtual List<Comment> Comments { get; set; }
}

This destination object i want to map the source to

 public class PostResponse
{
    public int PostId { get; set; } 
    public string PostTitle { get; set; } 
    public  IEnumerable<CommentObj> Comments { get; set; }
} 

This is the Controller throwing the error AutoMapper.AutoMapperMappingException: Error mapping types.

    [HttpGet(ApiRoutes.Posts.GetAll)]
    public async Task<IActionResult> GetAll()
    { 
            var posts = await _postServices.GetPostsAsync();
            return Ok(_mapper.Map<List<PostResponse>>(posts)); 
    }

This is the Service

    public async Task<List<Post>> GetPostsAsync()
    { 
            var queryable = _dataContext.Posts.AsQueryable();
            var psts = await queryable.Include(x => x.Comments).ToListAsync();
            return psts; 
    }

This is the Mapping Profile

    public DomainResponseProfile()
    {

        CreateMap<Post, PostResponse>().
        ForMember(dest => dest.Comments, opt => opt.MapFrom(src => src.Comments.Select(x => new CommentResponse
        { PostId = x.PostId, DateCommented = x.DateCommented })));
    }

This is the Domain Comment Object

public class Comment
{ 
    public int CommentId { get; set; }
    public int PostId { get; set; }  
}

This is the Response Comment Object

 public class CommentResponse
{
    public int CommentId { get; set; } 
    public List<CommentObj> Comments { get; set; }
}

I just found out what I did wrong.

 wrong  

CreateMap<Post, PostResponse>().
    ForMember(dest => dest.Comments, opt => opt.MapFrom(src => src.Comments.Select(x => new CommentResponse
    { PostId = x.PostId, DateCommented = x.DateCommented })));

right

   CreateMap<Post, PostResponse>().
        ForMember(dest => dest.Comments, opt => opt.MapFrom(src => 
  src.Comments));

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