新闻组中的新闻总数

时间:2015-08-30 08:18:56

标签: c# asp.net-mvc linq

我有两种模式:

  1. GroupNews

  2. 消息

  3. 我想通过局部视图查看列出的群组新闻,并显示与此群组相关的新闻数量

    在groupnews模型中:

    public long GroupId { get; set; }
    public string Name { get; set; }
    
    新闻模型中的

    public long newsId { get; set; }
    public string Title { get; set; }
    
    public long GroupId { get; set; }
    
    控制器中的

    public ActionResult Index()
    {
        var db = new ApplicationDbContext()
        var CountNews = from p in db.tbl_GroupNews
                        let cCount = (from c in db.tbl_News
                                      where p.GroupId== c.GroupId
                                      select c
                                     ).Count()
                        select new { GroupId= p.GroupId, coun = cCount }
    
        ViewBag.CountNews= CountNews.Count()}
    

    和我的部分视图

    @foreach (var item in Model){
    
    <div class="info-box">
    
        <div class="info-box-content">
            <span class="info-box-text">@item.Name::count of news in this group </span>
            <span class="info-box-number">
             @ViewBag.CountNews
            </span>
    
    
        </div><!-- /.info-box-content -->
    </div><!-- /.info-box -->}
    

1 个答案:

答案 0 :(得分:0)

如果您在数据库中使用外键,那么您只需通过以下方式获取计数:

 var db = new ApplicationDbContext()
var CountNews = db.tbl_GroupNews.News.Count();
ViewBag.Counter = CountNews;

and if you are not using lazy loading then can get by
var db = new ApplicationDbContext()
var CountNews = db.tbl_GroupNews.Include(w=>w.News).News.Count();
ViewBag.Counter = CountNews;

此外,我还有另一种选择,您可以获取新闻组的所有数据:

var db = new ApplicationDbContext();
var model = db.groupnew.include(w=>w.News).tolist();

在部分视图中,您可以使用:

@foreach (var item in Model){

<div class="info-box">

    <div class="info-box-content">
        <span class="info-box-text">@item.Name::count of news in this group </span>
        <span class="info-box-number">
         @item.News.Count()
        </span>


    </div><!-- /.info-box-content -->
</div><!-- /.info-box -->}