Linq查询以选择嵌套子代

时间:2018-10-28 04:38:00

标签: c# entity-framework linq

我有一个多层次的类结构。也就是说,一个“主题”可以有多个孩子,而一个“主题”可以属于多个父母。这是我的课程结构:

public abstract class Hierarchy <T>{
 public virtual ICollection<T> Parents { get; set; }
 public virtual ICollection<T> Children{ get; set; }
}

public class Topic: Hierarchy <T>
{
  public long ID {get;set;}
  public string Title{get;set;}
}

现在针对每个主题以及ID,标题,我要选择所有子ID(还应包括嵌套的子ID)。

这是我的查询

var result = from x in db.topics
             select new TopicsDO{
             Id = x.Id,
             Title = x.Title,
             ChildIds = x.Children.SelectMany(x=>x.Id) //This does not give nested child Ids, it just returns the immediate child Ids.
             }   

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您是否正在使用EntityFramework?那么您可以使用DbContext提供的更高级别的功能来实现您想要实现的目标,例如:

using (var context = new TopicContext())
{
  var topicsDO = context.Topics
    .Include(t=> t.Childrens)
    .Select(a => new
    {
        Id = a.BlogId,
        Title= a.Url,
        ChildrenIds = a.Children.Select(x => x.Id).ToArray()
    })
    .ToList();
}

如果您决定使用sql,则可以使用Join table Children来实现您的目标。

var result = from x in db.topics
            Join y in db.childrens On x.Id equals y.topicId Into childrenGroup
         select new TopicsDO{
         Id = x.Id,
         Title = x.Title,
         ChildrenGrp = childrenGroup
         }