数据库表结构设计:
声明:该表一些字段是外键字段,此功能只是该项目中一部分。如有兴趣可去Gitee下载该项目https://gitee.com/bingyu-code/news
UserId:用户Id NewsId:新闻Id NewsCommentId:上级评论Id 如果是一级评论就设置为NULL
一条新闻可以有多个一级评论,一个一级评论可以多个二级评论,一直到N级评论。可以看得出来这是一种树的结构。所以当你加载评论的时候就可以看做是在查找多个树
static void Main(string[] args)
{
List<NewsComment> res = new List<NewsComment>();
GetNewsComment(0, res);//res就保存了新闻Id为1的所有评论
}
/// <summary>
/// 递归获取所有评论
/// </summary>
public static void GetNewsComment(int newsCommentId,List<NewsComment> res)
{
var comments = GetNewsComments(newsCommentId);//第N级评论
foreach (var item in comments)//遍历N级评论获取N+1级评论
{
res.Add(item);
GetNewsComment(item.Id,res);
}
}
/// <summary>
/// 查询评论的子评论
/// </summary>
/// <returns></returns>
public static List<NewsComment> GetNewsComments(int newsCommentId)
{
string sql = "select * from NewsComment where NewsId=1";//这里查询新闻Id为1的评论
List<NewsComment> newsComments = new List<NewsComment>();
if (newsCommentId > 0)
sql += " and NewsCommentId="+newsCommentId;
else
sql += " and NewsCommentId is null";
var reader = SQLHelper.ExecuteReader(sql);
while (reader.Read())
{
newsComments.Add(Reflect<NewsComment>.GetModel(reader));
}
reader.Close();
return newsComments;
}
}