Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于年/月的实体框架后归档列表_Sql_View_Asp.net Mvc 5_Entity Framework 6_Viewbag - Fatal编程技术网

Sql 基于年/月的实体框架后归档列表

Sql 基于年/月的实体框架后归档列表,sql,view,asp.net-mvc-5,entity-framework-6,viewbag,Sql,View,Asp.net Mvc 5,Entity Framework 6,Viewbag,我想做一个简单的博客文章归档列表,如下所示 2014年 一月(一) 2013年 十二月(一) 11月(14日)->链接到带日期的搜索 十月三日 五月五日 四月三日 我需要通过ViewBag.Archives发送此文件。当我在SQLServerManagementStudio中执行以下SQL时 select year(Created) as PostYear, datename(month,Created) as PostMonth,count(ID) as ArticleAmount f

我想做一个简单的博客文章归档列表,如下所示

2014年

  • 一月(一)
2013年

  • 十二月(一)
  • 11月(14日)->链接到带日期的搜索
  • 十月三日
  • 五月五日
  • 四月三日
我需要通过ViewBag.Archives发送此文件。当我在SQLServerManagementStudio中执行以下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>
}
@foreach(ViewBag.Archives中的变量项)
{
@项目.年份

}
错误:其他信息:“对象”不包含“年”的定义


谢谢你

你在找这样的东西吗:

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();
编辑

  • 在select:)上使用ToList()
  • 尝试使用对象或模型来存储数据,这也会使在视图中访问时添加月份名称变得更容易。下面的示例将“ObjectName()”替换为“PostGroup”:
公共类留言薄{
公共整数计数{get;set;}
公共整数年{get;set;}
公共整数月份{get;set;}
}

PS:很抱歉格式错误,仍在学习:)