如何在每天的TextBox控件中使用linq显示每天的总小时数?

时间:2014-12-17 16:58:51

标签: c# asp.net linq linq-to-entities

我是LINQ-to-Entities世界的新手,我正在尝试显示(本周每天每项任务的小时数) 在TextBox中,指定每天的总小时数。

我在数据库中有以下表格:

Task Table: TaskId, Description
Sheet Table: SheetId, WeekNumber
SheetEntry Table: SheetEntryId, SheetId, TaskId
EntryDetail Table: EntryDetailId, SheetEntryId, WorkDay, Hours

我的aspx页面中有以下TextBox:

<asp:TextBox ID="txtSun" runat="server" CssClass="input-mini" placeholder="Sunday's Total"></asp:TextBox>
<asp:TextBox ID="txtMon" runat="server" CssClass="input-mini" placeholder="Monday's Total"></asp:TextBox>
<asp:TextBox ID="txtTue" runat="server" CssClass="input-mini" placeholder="Tuesday's Total"></asp:TextBox>
<asp:TextBox ID="txtWed" runat="server" CssClass="input-mini" placeholder="Wednesday's Total"></asp:TextBox>
<asp:TextBox ID="txtThu" runat="server" CssClass="input-mini" placeholder="Thursday's Total"></asp:TextBox>
<asp:TextBox ID="txtFri" runat="server" CssClass="input-mini" placeholder="Friday's Total"></asp:TextBox>
<asp:TextBox ID="txtSan" runat="server" CssClass="input-mini" placeholder="Saturday's Total"></asp:TextBox>

我编写了以下LINQ查询,该查询显示了一周中每天的总小时数,但我不确定它是否运行良好:

var query = (from detail in context.EntryDetail
                            group detail by new { detail.Workday } into g
                            select new {
                                Date = g.Key.Workday,
                                Total = g.Sum(x => x.Hours)
                            }).ToList();

那么如何在指定的TextBox控件中显示每天的总小时数?

请注意,本周从星期日开始。

1 个答案:

答案 0 :(得分:1)

编写查询的最佳方式是:

这将只给出总小时数 var query1 = context.EntryDetail.GroupBy(_x =&gt; _x.WorkDay).Select(_x =&gt; _x.Sum(c =&gt; c.Hours))。ToList();

这将给出一对形式。
var query2 = context.EntryDetail.GroupBy(_x =&gt; _x.WorkDay).Select(_x =&gt; new {day = _x.Key,totalhours = _x.Sum(c =&gt; c.Hours)})。ToList ();

然后,您可以根据此查询中的日期添加到文本框中。

foreach(query2中的var项)
            {
                开关(item.day)
                {
                    案例&#34;星期天&#34; :texSun.Text = item.totalhours;
                    打破;
                    案例&#34;星期一&#34; :texMon.Text = item.totalhours;
                    打破;
                    //与其他情况类似                 }
             }