我有一个评论列表作为我网站上每节课的参数。我尝试了许多不同的方法(如下所示)来检索注释的数量。我的模型的结构如下所示:
public class EducateLesson
{
[Key]
public int EducateLessonID { get; set; }
public EducateTopics Topic { get; set; }
public string Title { get; set; }
public string Introduction { get; set; }
public string Body { get; set; }
public string VideoURL { get; set; }
public int Likes { get; set; }
public virtual List<Comment> Comments { get; set; }
public void AddComment(Comment c)
{
Comments.Add(c);
}
}
public class Comment
{
[Key]
public int CommentID { get; set; }
public DateTime Date { get; set; }
public string IdentityUserName { get; set; }
public string Text { get; set; }
}
我注意到Comment类在这里没有FK到课程对象。
这些是我尝试检索视图中单个课程计数的方法:
count = (from l in lesson.Comments select l).Count();
@lesson.Comments.Count()
@lesson.Comments.Count
答案 0 :(得分:0)
我在不改变模型的情况下解决了这个问题。对这篇文章的评论实际上并不有益。首先,我将其添加到我的存储库类:
public int CommentCount(int id)
{
EducateLesson lesson = context.EducateLessons.Find(id);
return lesson.Comments.Count;
}
接下来,我通过创建一个存储库类并对每个课程对象使用此方法来计算:
int count = 0;
EducateRepository EducateRepository = new EducateRepository();
count = EducateRepository.CommentCount(lesson.EducateLessonID);