【问题标题】:Linq query to select nested children用于选择嵌套子项的 Linq 查询
【发布时间】:2018-10-28 04:38:00
【问题描述】:

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

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.
             }   

感谢您的帮助。

【问题讨论】:

标签: c# entity-framework linq


【解决方案1】:

您在使用 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
         } 

【讨论】:

  • 嗨@Joe,感谢您的帮助。我正在使用实体框架,您提供的解决方案返回直接子 ID。我需要层次结构中所有可用子项的 ID。
  • 我明白了。我没有正确阅读问题。我认为您可以尝试使用 context.ExecuteQuery 来执行 sql 查询。在查询中,尝试使用 Cross Apply
猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 2013-01-19
  • 1970-01-01
相关资源
最近更新 更多