【发布时间】:2022-03-09 19:09:03
【问题描述】:
我正在使用具有如下模型实现递归的 .NET MVC:
public class Comment
{
[Key]
[Required]
public int CommentId { get; set; }
[Required]
public string Content { get; set; }
public bool Anonymous { get; set; }
[Required]
public DateTime Created_date { get; set; }
[Required]
public DateTime Last_modified { get; set; }
public virtual Comment Reply { get; set; }
public virtual ICollection<Comment> Replys { get; set;}
public virtual Idea Idea { get; set; }
}
在说明中,每个idea里面都包含了不同的Comment,每个comment还有几个较小的Comment来回复前一个。但是,我不知道如何进行递归以获取评论的回复和每个回复的较小回复,直到控制器中的最后一个回复以及如何在视图中显示它们。由于我的解释有时不清楚,请随时问我任何问题。
public ActionResult Index(int? i)
{
List<Idea> Ideas = db.Ideas.ToList();
foreach(Idea idea in Ideas)
{
idea.Comments = db.Comments.Include(x => x.Reply).ToList();
idea.Comments=idea.Comments.Where(x => x.Idea == idea).ToList();
foreach (Comment comment in idea.Comments)
{
comment.Replys = GetComments(comment.CommentId); //This function use to get list of reply for comment
foreach (Comment reply in comment.Replys)
{
reply.Replys=GetComments(reply.CommentId);
foreach (Comment reply2 in reply.Replys)
{
reply2.Replys=GetComments(reply2.CommentId);
foreach(Comment reply3 in reply2.Replys)
{
reply3.Replys = GetComments(reply3.CommentId);
//When would this stop ?
}
}
}
}
}
return View(Ideas.ToPagedList(i ?? 1, 5));
}
【问题讨论】:
-
你已经用这个
public virtual ICollection<Comment> Replys做对了。您可能只需要添加一个可为空的int? ReferenceCommentId -
我已经在控制器中添加了我的问题,以便您更容易理解
标签: c# asp.net-mvc recursion