当我尝试访问我的 Comment 类上的 Author 属性时,它始终为空。我试过在我的查询中使用 Include() 并且安装了延迟加载代理也无济于事。我正在使用带有 .NET 5 的最新版本的 Asp.net 核心。 这是我的评论课:
public class Comment {
public virtual int Id { get; set; }
public virtual int PostReplyToId { get; set; }
public virtual Post PostReplyTo { get; set; }
public int? ReplyToId { get; set; }
public virtual Comment ReplyTo { get; set; }
public virtual ICollection<Comment> Replies { get; set; }
public virtual string AuthorId { get; set; }
public virtual ApplicationUser Author { get; set; }
public virtual DateTime TimePosted { get; set; }
public virtual string Content { get; set; }
public virtual bool Visible { get; set; }
[NotMapped]
public string CommentInvalid { get; set; }
}
这是我的 ApplicationUser 类:
public class ApplicationUser : IdentityUser {
[ForeignKey("AuthorId")]
public virtual ICollection<Post> PostsAuthored { get; set; }
[ForeignKey("AuthorId")]
public virtual ICollection<Comment> CommentsAuthored { get; set; }
}
这是我访问评论的作者属性的视图部分(我在这里得到 NullReferenceException,因为 comment.Author 为空):
<div>
<h4>Comments</h4>
<p><a href="#" class="CommentReplyButton" data-commentId="null">Create a comment</a></p>
@foreach (Comment comment in (List<Comment>)ViewBag.Comments) {
if (comment.ReplyToId == null) {
<div class="media" id="@("Comment" + comment.Id)">
<a href="#"><img class="mr-3" src="~/images/pfp.png" alt="@comment.Author.Id's Profile Picture" /></a> <!-- NullReferenceException here -->
我用来设置 ViewBag.Comments 的查询是这样的(我不认为 Include 是必要的,因为没有它我也有同样的问题):
List<Comment> comments = (from comment in _context.Comment.Include(e => e.Author)
where comment.PostReplyToId == post.Id
select comment).ToList();
ViewBag.Comments = comments;
我运行了 Serge 的查询,结果发生了同样的事情。这是视觉工作室所说的评论等于(ViewBag.Comments 只是一个 1 个元素的长列表) Query Result 我知道评论绝对不为空,因为我可以从上面的行中成功获取 Id。我检查了数据库,我知道在评论中正确设置了 AuthorId,并且评论的 AuthorId 字段设置正确。我知道它应该指向的 ApplicationUser 存在,因为它在数据库中,我可以用它登录。 感谢大家的帮助。