对于确定将Linq to Entities用于我的应用程序的正确方法,我将不胜感激。具体来说,在处理多个多对多表时,我很难理解分组。
简化的数据库设计是:
http://imageshack.us/a/img443/5863/entitydesignerdiagram.png
数据库设计理念:
人物:有权编辑多个统计信息的个人。 季节:按统计数据分组的时间段,例如2012年棒球或2012年。 玩家:参与统计的人或个人。这里需要的只是实体的名称。比如Kevin Wasie,或者Varsity Team 统计:保存属于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以获得所需的结果?
非常感谢任何帮助,包括教程或其他信息的链接。提前谢谢!
答案 0 :(得分: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
})
});