2017-04-05 18 views
0

每個條目計數我有一個用戶表和社區表。用戶可以加入多個社區,社區可以擁有多個用戶。所以我有一個名爲CommunityUser表的關係表。 CommunityUser表具有UserIDCommunityID定義哪個用戶註冊在哪個社區。 我想表明我的搜索視圖This is somewhat same as Facebook Groups檢索針對一個表中從某些其他表在單個視圖中MVC

我展示社區標誌標題細節從社區表與@foreach循環,但我還想添加計數來自CommuntyUser表的每個communityID。 這裏是我的社區模型類

public class Community 
{ 
    [Key] 
    public int CommunityID { get; set; } 

    [Required] 
    public string CommunityName { get; set; } 

    public string CommunityAbout { get; set; } 

    public string CommunityLogo { get; set; } 

    public int PrivacyID { get; set; } 

    //I am trying to get members count using this 
    public virtual IEnumerable<CommunityUser> CommunityUsers { get; set; } 


} 

這裏是我的控制器函數,其中我申請這個

public ActionResult ShowSearchResults(string SearchQuery) 
    { 


     var communitySearch = from m in db.Communities 
           select m; 

     if (!String.IsNullOrEmpty(SearchQuery)) 
     { 
      communitySearch = communitySearch.Where(s => s.CommunityName.Contains(SearchQuery)); 
     } 



     return View(communitySearch); 
    } 

這是我的看法。我已經刪除了額外的代碼,並提到我需要從CommunityUser Table中計數。

@foreach (var item in Model) 
{ 


    <div class="row"> 


     <div class="col-md-4"> 

      @Html.DisplayFor(modelItem => item.CommunityName) 
      <br> 
      @ViewBag.Count 

    <!--Need to count of members in that community--> 
    <!--means How many times that communityID appeared in CommunityUser table--> 

     <br> 
     @Html.DisplayFor(modelItem => item.CommunityAbout) 

    </div> 

</div> 

}

回答

0

一個快速解決我能想到的是 創建裏面應該有以下屬性的新模式,我將其命名爲是CommunityWithUserCount

  • 社區
  • USERCOUNT位

之後,改變你現有的鱈魚e to follwoing

var communityQuery = db.Communities.Include("CommunityUsers").AsQueriable(); 
    if (!String.IsNullOrEmpty(SearchQuery)) 
    { 
     communityQuery = communityQuery.Where(s => s.CommunityName.Contains(SearchQuery)).AsQueriable(); 
    } 

var yourCustomObject = communityQuery.Select(elem => new CommunityWithUserCount() 
{ 
Community = elem, 
Count = elem.CommunityUser.Count() 
}).ToList(); 

我希望這對你有效。我不得不編譯/測試這個代碼。這只是我認爲可以解決您的問題的一個想法。

+0

如何在我的視圖類中訪問此計數列表? –

+0

現在,不要傳遞舊模型,只需傳遞此自定義模型,就可以獲得社區用戶數。 – Naveen

相關問題