具有父子关系的Linq到sql查询

本文关键字:sql 查询 Linq 父子关系 | 更新日期: 2023-09-27 18:17:22

我有以下模型发布问题和回答的问题

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查询来实现这个呢?

具有父子关系的Linq到sql查询

首先你需要把你的模型改成这样

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);
        }