Linq to sql查询与Parent子关系

时间:2016-11-11 12:55:21

标签: c# entity-framework linq asp.net-core-mvc

我有以下模型发布问题并回复问题

模型

PORT´,

当用户发布新问题时,“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”。

基本上ClassDiscussionID和ParentClassDiscussionID列具有父子关系。

但是,我想显示像DiscussionTitle,ReplyCount这样的数据如下

ParentClassDiscussionID

那么,如何使用linq to sql查询实现这一目标呢?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

首先,您需要将模型更改为此类

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