新闻组中的Total News

本文关键字:News Total 新闻组 | 更新日期: 2023-09-27 18:10:20

我有两个模型:

  1. GroupNews

  2. 新闻

我想列出组新闻在视图的部分视图,并显示有多少新闻相关的组

in groupnews model:

public long GroupId { get; set; }
public string Name { get; set; }

in News Model

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 -->}

新闻组中的Total News

如果您使用的是外键的数据库,那么您可以获得计数只需:

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

在partial视图中,你可以使用:

@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 -->}