【发布时间】:2020-02-05 19:33:03
【问题描述】:
这是我要映射的源对象
public class Post
{
public string PostId { get; set; }
public string PostTitle { get; set; }
public virtual List<Comment> Comments { get; set; }
}
我想将源映射到这个目标对象
public class PostResponse
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public IEnumerable<CommentObj> Comments { get; set; }
}
这是控制器抛出错误 AutoMapper.AutoMapperMappingException: 错误映射类型。
[HttpGet(ApiRoutes.Posts.GetAll)]
public async Task<IActionResult> GetAll()
{
var posts = await _postServices.GetPostsAsync();
return Ok(_mapper.Map<List<PostResponse>>(posts));
}
这是服务
public async Task<List<Post>> GetPostsAsync()
{
var queryable = _dataContext.Posts.AsQueryable();
var psts = await queryable.Include(x => x.Comments).ToListAsync();
return psts;
}
这是映射配置文件
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 })));
}
这是域评论对象
public class Comment
{
public int CommentId { get; set; }
public int PostId { get; set; }
}
这是响应评论对象
public class CommentResponse
{
public int CommentId { get; set; }
public List<CommentObj> Comments { get; set; }
}
【问题讨论】:
-
你可能有循环引用。父指向子,子指向父。您要么需要将它们取出,使用最大深度/永久引用,要么手动映射并忽略导致这种情况的属性。还要检查 CommentObj 模型,或者你也可以在这里发布。
-
你花了多少时间研究这个?自己做这件事要花多少时间?
标签: c# .net-core entity-framework-core automapper