2017-04-05 21 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

相关问题