commentsummary信息汇总
1.创建模型GuestbookEntry
public class GuestbookEntry
{
public int Id { get; set; }
public string Name { get; set; }
public string Comment { get; set; }
public string Reply { get; set; }
public DateTime CreatedOn { get; set; }
}
2.创建模型CommentSummary
public class CommentSummary
{
public string UserName { get; set; }
public int NumberofComments { get; set; }
}
3.创建数据库上下文类
public class VMContext:DbContext
{
public DbSet<GuestbookEntry> Entries { get; set; }
}
4.数据迁移:视图->其它窗口->程序包管理器
enable-
add-
update-
webconfig中的connectionstring中的名字与数据库上下文类的名字相同
5.创建控制器GuestbookController
public class GuestbookController : Controller
{
VMContext _db = new VMContext();
public ActionResult CommentSummary()
{
var entries = from entry in _db.Entries
group entry by entry.Name into groupedByName
orderby groupedByName.Count() descending
select new CommentSummary
{
NumberofComments=groupedByName.Count(),
UserName=groupedByName.Key
};
return View(entries.ToList());
}
}
6.创建视图CommentSummary
@model IEnumerable<MvcGuestBook.Models.CommentSummary>
@{
ViewBag.Title = "CommentSummary";
}
<h2>CommentSummary</h2>
@*<p>
@Html.ActionLink("Create New", "Create")
</p>*@
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
<th>
@Html.DisplayNameFor(model => model.NumberofComments)
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserName)
</td>
<td>
@Html.DisplayFor(modelItem => item.NumberofComments)
</td>
</tr>
}
</table>