如何使用Linq显示多个表中的数据。 [英] How Do I Display Data From More Than One Table Using Linq.
问题描述
我有以下型号和表格
public class 学生
{
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 ;}
}
我需要实现的是计算在我的控制器中使用数据操作方法在Data.cshtml视图中显示多少学生,多少个俱乐部和多少个房子并显示它们
i然后创建了一个模型来获取数据
public class 数据
{
public int StudCount { get ; set ; }
public int ClubCount {获得跨度>; set ; }
public int HouseCount {获得跨度>; set ; }
}
如何编写linq语句以便能够计算不定义学生,没有俱乐部的,并没有从不同的充表
假设你有一个的DbContext(YourDbContext),并使用的DbContext可以编写查询作为下面:
使用( var dbc = new YourDbContext())
{
var noofstudents = dbc.Students。选择(s = > s.StudentId).Count();
var noofclubs = dbc.Clubs.Select(s => s.ClubId).Count();
var noofhosues = dbc.Houses.Select(s => s.HouseId).Count();
}
我认为你的第三个模特课是House而不是学生。
作为ids在每个表中都是主要的(假设),计数将返回你期望的值。
我也使用了复数形式的类作为表名,你替换它们,因为它们在你的名字中命名数据库。
希望这会有所帮助。
i have the following model and table
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
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
Assuming you have a DbContext (YourDbContext) defined and using the DbContext you can write the queries as below:
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.
这篇关于如何使用Linq显示多个表中的数据。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!