1

在确定将 Linq to Entities 用于我的应用程序的正确方法方面,我将不胜感激。具体来说,在处理多个多对多表时,我很难理解分组。

简化的数据库设计是:

http://imageshack.us/a/img443/5863/entitydesignerdiagram.png

数据库设计理念:

人员:有权编辑多个统计数据的个人。季节:分组统计数据的时间段,例如 2012 年棒球或 2012 年。参与者:参与统计的个人或群体。这里需要的只是实体的名称。例如 Kevin Wasie 或 Varsity Team Statistics:保存属于 1 个赛季的个人统计信息,例如达阵或本垒打。

代码背后:

    Dim stats = From st In pl.statistics From per In st.people
      Where per.id.Equals(personID)
      Select New With
            {.season_name = st.season.name, .statistic_name = st.name, .season_id = st.season.id,
             .players = From play In pl.players
                             Where play.seasonId = st.season.id
                             Select New With {.player_name = play.name}}

    rep_statistics.DataSource = stats
    rep_statistics.DataBind()

.aspx:

<asp:Repeater ID="rep_actions" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<b><%# Eval("season_name")%></b> - <%# Eval("statistic_name")%><br />
    <asp:Repeater ID="rep_part" runat="server" DataSource='<%# Eval("players")%>'>
    <itemtemplate>
    <%# Eval("participantname")%>
    </itemtemplate>
    <SeparatorTemplate>,</SeparatorTemplate>
    </asp:Repeater>
</ItemTemplate>
</asp:Repeater>

期望的结果是按季节分组显示页面,如下所示:

Season 1
   Statistic 1
      Season1 Players
   Statistic 2
      Season1 Players
   Statistic 3
      Season1 Players
Season 2
   Statistic 4
      Season 2 Players
...

目前的结果是:

Season 1
   Statistic 1
      Season1 Players
Season 1
   Statistic 2
      Season1 Players
Season 1
   Statistic 3
      Season1 Players
Season 2
   Statistic 4
      Season 2 Players
...

如何修改 linq 以获得所需的结果?

任何帮助,包括指向教程或其他信息的链接,将不胜感激。先感谢您!

4

1 回答 1

3

下面是 C# 代码,但我希望它能给你一个关于你需要做什么的提示。该查询过滤具有给定值的人,Id并用于SelectMany()选择这些人的统计信息。

然后,它将选定的统计数据分组SeasonId并填充要输出的季节集合。

var data = st.People
             .Where(p => p.Id == personID)
             .SelectMany(p => p.Statistics)
             .GroupBy(s => s.SeasonId)
             .Select(g => new
             {
                 SeasonId = g.Key,
                 SeasonName = g.Fist().Season.Name,
                 Statistics = g.Select(s => new
                               {
                                   StatisticId = s.Id,
                                   StatisticName = s.Name,
                                   Players = s.Season.Players
                               })
             });
于 2012-11-18T20:06:22.480 回答