我有以下发布问题的模型并回答问题
模型
public partial class LMS_Question
{
[Key]
public int ClassDiscussionID { get; set; }
public int? ParentClassDiscussionID { get; set; }
public string Discussion { get; set; }
public string DiscussionTitle { get; set; }
}
当用户发布新问题时,“
ParentClassDiscussionID
”将为空,并且如果对该问题添加了任何答复,则“ ClassDiscussionID
”将更新为“ ParentClassDiscussionID
”。基本上,ClassDiscussionID和ParentClassDiscussionID列具有父子关系。
但是,我想显示如下数据,例如:DiscussionTitle,ReplyCount
DiscussionTitle ReplyCount
-------------------------
Question1 2 Reponses
Question2 3 Reponses
Question3 5 Reponses
那么,如何使用linq to sql query实现此目的?
谢谢您的帮助 !
最佳答案
首先,您需要将模型更改为如下所示
public partial class LMS_ClassDiscussion
{
public LMS_ClassDiscussion()
{
LMS_ClassDiscussionchild = new List<LMS_ClassDiscussion>();
}
public int ClassDiscussionID { get; set; }
public int? ParentClassDiscussionID { get; set; }
public string Discussion { get; set; }
public string DiscussionTitle { get; set; }
public LMS_ClassDiscussion _LMS_ClassDiscussion { get; set; }
public List<LMS_ClassDiscussion> LMS_ClassDiscussionchild { get; set; }
}
那你就需要办法让所有父母的孩子
public List<LMS_ClassDiscussion> GetChildren(IList<LMS_ClassDiscussion> source, int? parentId)
{
var children = source.Where(x => x.ParentClassDiscussionID == parentId).ToList();
//GetChildren is called recursively again for every child found
//and this process repeats until no childs are found for given node,
//in which case an empty list is returned
children.ForEach(x => x.LMS_ClassDiscussionchild = GetChildren(source, x._LMS_ClassDiscussion.ClassDiscussionID));
return children.ToList();
}
这样调用方法
var LMS_ClassDiscussions = GetChildren(query, null);
foreach (var item in LMS_ClassDiscussions)
{
Console.WriteLine(item._LMS_ClassDiscussion.ClassDiscussionID + "="+item.LMS_ClassDiscussionchild.Count);
}