LINQ分组帮助

时间:2010-10-06 03:09:56

标签: linq

我有一个数据库表,其中包含父类和子记录,就像类别表一样。此表的ParentID字段包含该记录的父记录的ID ...

我的表格列是:SectionID,Title,Number,ParentID,Active

我只打算允许我父母与孩子的关系深入两级。所以我有一个部分和一个子部分,并且它。

我需要以大纲的方式将这些数据输出到我的MVC视图页面中......

  1. 第1节
    • 第1小节第1节
    • 第2分之一
    • 第3分之一
  2. 第2节
    • 第1分之二
    • 第2分,共2条
    • 第3分类
  3. 第3节
  4. 我正在使用Entity Framework 4.0和MVC 2.0,并且从未尝试使用LINQ这样的东西。我在section表上设置了一个FK,将ParentID映射回SectionID,希望EF能够创建一个复杂的“Section”类型,Sub-Sections作为Sections类型列表的属性,但也许我没有正确设置。

    所以我猜我仍然可以使用LINQ查询获得最终结果。有人能指出一些可以提供解决方案或可能提示正确方向的示例代码吗?

    alt text

    更新

    我能够理顺我的EDMX,以便我可以将每个部分的子部分作为类型列表的属性,但现在我意识到我需要对相关实体进行排序。

    var sections = from section in dataContext.Sections
                           where section.Active == true && section.ParentID == 0
                           orderby section.Number
                           select new Section
                           { 
                            SectionID = section.SectionID,
                            Title = section.Title,
                            Number = section.Number,
                            ParentID = section.ParentID,
                            Timestamp = section.Timestamp,
                            Active = section.Active,
                            Children = section.Children.OrderBy(c => c.Number)
                           };
    

    产生以下错误。 无法将类型'System.Linq.IOrderedEnumerable'隐式转换为'System.Data.Objects.DataClasses.EntityCollection'

2 个答案:

答案 0 :(得分:1)

您的模型有两个导航属性Sections1Section1。将第一个重命名为Children,将第二个重命名为Parent

根据您是否有一个root部分或者每个顶级部分都是自身的父级(或者改为使父级可以为空?),您的查询可能类似于: -

  // assume top sections are ones where parent == self
  var topSections = context.Sections.Where(section => section.ParentId == SectionId);

  // now put them in order (might have multiple orderings depending on input, pick one)
  topSections = topSections.OrderBy(section => section.Title);

  // now get the children in order using an anonymous type for the projection
  var result = topSections.Select(section => new {top = section, children = section.Children.OrderBy(child => child.Title)});

答案 1 :(得分:1)

对于一些linq示例:

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

这几乎涵盖了所有linq操作,特别关注GroupBy。关键是要理解每件作品的输入和输出,以便串联编排几个,没有捷径,但要了解他们做了什么,这样你就知道手头有什么。 Linq表达式只是这些操作与一些语法糖的组合。

相关问题