按日期分组并选择声明

时间:2014-04-12 02:50:18

标签: c# linq date group-by linq-to-entities

我想要做的就是从我的评论表中选择所有项目并按日期分组。我最后的选择声明正在破裂,因为“当前上下文中不存在审核”。我做错了什么?

var byDate = from review in myEntities.Reviews
             let date = review.CreateDateTime
             group review by EntityFunctions.TruncateTime(date) into g
             orderby g.Key
             select new { review.Id, review.CreateDateTime, review.Summary, review.Body };
repeater1.DataSource = byDate;
repeater1.DataBind();

2 个答案:

答案 0 :(得分:0)

在查询结束时,您有群组,而不是单个值。因此,您无法执行此操作review.Id,除了审核不存在您需要使用g,因为您将它们分组为g

from review in myEntities.Reviews
let date = review.CreateDateTime
group review by EntityFunctions.TruncateTime(date) into g
orderby g.Key
select new { Date = g.Key, Rewiews = g.ToList() };

如果这是您第一次使用groupby,我建议您阅读文档并查看示例:Group Elements in a Sequence

答案 1 :(得分:0)

以下是我在我的代码隐藏文件中所做的事情:

var byDate = (from review in myEntities.Reviews
              group review by review.CreateDateTime into dateGroup
              select new
              {
                 dateGroup.Key,
                 Reviews = from review in myEntities.Reviews
                           where review.CreateDateTime.Day == dateGroup.Key.Day &&
                           review.CreateDateTime.Month == dateGroup.Key.Month &&
                           review.CreateDateTime.Year == dateGroup.Key.Year   
                           select new { review.CreateDateTime, review.Title }
               });

Repeater1.DataSource = byDate;
Repeater1.DataBind();

然后在我的aspx页面上:

<asp:Repeater ID="Repeater1" runat="server">
   <ItemTemplate>
      <asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Key", "{0:MM/dd/yy}") %>' />
      <asp:BulletedList ID="ReviewList" runat="server" DataSource='<%# Eval("Reviews") %>' />
  </ItemTemplate>
</asp:Repeater>