【发布时间】:2021-10-07 09:37:50
【问题描述】:
当我尝试访问 Comment 类的 Author 属性时,它始终为 null。我尝试在查询中使用 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; }
}
这是我访问评论的 Author 属性的视图部分(我在这里得到 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 存在,因为它在数据库中,我可以使用它登录。 感谢大家的帮助。
【问题讨论】:
-
您特别尝试了哪些查询?
-
@abdusco 我已经更新了我的问题以包含我在其中使用的查询。
标签: c# asp.net-mvc entity-framework-core asp.net-identity