Click here to Skip to main content
15,917,859 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have the following model and table
C#
  public class Student
{
  public int StudentId{get;set;}
  public string StudentName{get;set;}
}

public class Club
{
  public int ClubId{get;set;}
  public string ClubName{get;set;}
}

public class House
{
  public int HouseId{get;set;}
  public string HouseName{get;set;}
}


what i need to acheive is to count how many students, how many clubs and how many house and display them in Data.cshtml view using Data action method in my controller

i then created a model to to get the data

C#
public class Data
    {
        public int StudCount { get; set; }

        public int ClubCount { get; set; }

        public int HouseCount { get; set; }

         
    }


how do i write a linq statement to be able to count no of student, no of club, and no of house from differnt tables
Posted
Updated 6-Jun-15 0:21am
v2
Comments
Mostafa Asaduzzaman 7-Jun-15 6:55am    
have you tried yet with Solution 1 ?
Member 11746146 8-Jun-15 17:26pm    
yes the solution helps
Member 11746146 8-Jun-15 17:25pm    
thanks the solution helped
Mostafa Asaduzzaman 8-Jun-15 17:31pm    
you are welcome.

1 solution

Assuming you have a DbContext (YourDbContext) defined and using the DbContext you can write the queries as below:
C#
using(var dbc = new YourDbContext())
{
var noofstudents= dbc.Students.Select(s => s.StudentId).Count();
var noofclubs = dbc.Clubs.Select(s=>s.ClubId).Count();
var noofhosues =dbc.Houses.Select(s=>s.HouseId).Count();
}


I think your third model class is House not student.
As the ids in each table are primary(assuming), the counts will return the values as you expect.
Also I have used the plural forms of the class as table names, you replace them as they are named in your database.

Hope this will help.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900