[英]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.这是控制器抛出错误 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.