我想制作一个简单的博客文章列表,如下所示
2014
2013
我需要通过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'的定义
谢谢
答案 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();
修改强>
public class GuestbookPost {
public int Count { get; set; }
public int Year { get; set; }
public int Month { get; set; }
}
PS:抱歉格式不好,还在学习:)