【问题标题】:Year/Month based Post Archive List With Entity Framework带有实体框架的基于年/月的存档列表
【发布时间】:2014-02-19 11:47:52
【问题描述】:

我想制作一个简单的博客文章存档列表,如下所示

2014

  • 1 月 (1)

2013

  • 十二月(1)
  • 11 月 (14) -> 链接到搜索日期
  • 10 月 (3)
  • 五月 (5)
  • 四月 (3)

我需要通过 ViewBag.Archives 发送这个。当我在 SQL Server Management Studio 中执行以下 SQL 时。

select year(Created) as PostYear, datename(month,Created) as PostMonth,count(ID) as ArticleAmount from Post group by year(Created), datename(MONTH,Created) order by PostYear, PostMonth

我明白了:

PostYear    PostMonth   ArticleAmount
2010        February    1
2011        September   1
2012        April       1
2012        February    1
2013        February    4
2013        March       1
2014        February    1

我的代码:

ViewBag.Archives = db.Posts
.GroupBy(group => new { group.Created.Year, group.Created.Month })
.Select(x => new { count = x.Count(), Year = x.Key.Year, Month = x.Key.Month });

我的观点:

@foreach (var item in ViewBag.Archives)
{
    <p>@item.Year</p>
}

错误:附加信息:“对象”不包含“年份”的定义

谢谢

【问题讨论】:

    标签: sql view asp.net-mvc-5 entity-framework-6 viewbag


    【解决方案1】:

    您是否正在寻找类似的东西:

    ViewBag.Archives = db.Posts
                .GroupBy(group => new {group.Created.Year, group.Created.Month})
                .Take(5)
                .Select(x => new GuestBookPost()
                {
                    count = x.Count,
                    Year = x.Key.Created.Year,
                    Month = x.Key.Created.Month
                }).ToList();
    

    编辑

    • 在选择上使用 ToList() :)。
    • 尝试使用对象或模型来存储数据,这也将更容易添加月份名称作为在视图中访问。下面的示例,将“ObjectName()”替换为“PostGroup”:

    public class GuestbookPost {
    public int Count { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    }

    PS:抱歉格式不好,还在学习中:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-25
      • 2014-12-27
      • 2015-02-13
      • 2014-08-10
      • 2014-03-29
      • 1970-01-01
      • 2015-12-26
      • 2017-06-15
      相关资源
      最近更新 更多