基于年/月的帖子列表与实体框架

时间:2014-01-28 09:09:10

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

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

2014

  • 1月(1)

2013

  • 十二月(1)
  • 十一月(14) - >链接到日期搜索
  • 十月(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>
}

错误:附加信息:'object'不包含'Year'的定义

谢谢

1 个答案:

答案 0 :(得分:0)

您正在寻找类似的东西:

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:抱歉格式不好,还在学习:)