asp.net mvc 遍历linq to sql 多表联查
两张表: 班级表和学生表: 最终想获得学生的姓名、密码、性别、年龄、住址、爱好、班级名称、班级所学方向
var temp=from a in _db.student
join b in _db.classes
on a.c_id equals b.id
select
new
{
Id=a.id,
Name = a.name,
Pwd = a.pwd,
Sex = a.sex,
Age = a.age,
Address = a.address,
Hobby = a.hobby,
StuName = b.name,
Direction = b.direction
}; 使用linq to sql来实现多表联查,问题就出来了,这里是推动类型,前台怎么绑定是个问题 那么是否可以创建一个类,包含这些字段呢?
public class Stu
{
public int Id { get; set; }
public string Name { get; set; }
public string Pwd { get; set; }
public bool? Sex { get; set; }
public int? Age { get; set; }
public string Address { get; set; }
public string Hobby { get; set; }
public string StuName { get; set; }
public string Direction { get; set; }
} 然后在多表联查的时候select new Stu(){} 具体代码:
var temp=from a in _db.student
join b in _db.classes
on a.c_id equals b.id
select
new Stu()
{
Id=a.id,
Name = a.name,
Pwd = a.pwd,
Sex = a.sex,
Age = a.age,
Address = a.address,
Hobby = a.hobby,
StuName = b.name,
Direction = b.direction
}; 这样就可以返回一个IQueryable.ElementType{Name="Stu",FullName="项目名称.Models.Stu"} 然后在 ViewData.Model = temp.ToList(); 这样就转换为IEnumerable<COOL.Models.Stu> 在view视图里面加上 @model IEnumerable<COOL.Models.Stu> @foreach (var item in Model)进行遍历即可 效果: 呈上Controller完整代码:
public class HomeController : Controller
{
readonly StudentDataContext _db=new StudentDataContext();
// GET: /Home/
public ActionResult Index()
{
var temp=from a in _db.student
join b in _db.classes
on a.c_id equals b.id
select
new Stu()
{
Id=a.id,
Name = a.name,
Pwd = a.pwd,
Sex = a.sex,
Age = a.age,
Address = a.address,
Hobby = a.hobby,
StuName = b.name,
Direction = b.direction
};
ViewData.Model = temp.ToList();
return View();
}
}
view 视图的完整代码:
@model IEnumerable<COOL.Models.Stu>
@using System.Collections
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table border="1" cellpadding="0" cellspacing="0">
<tr>
<th></th>
<th>
姓名
</th>
<th>
密码
</th>
<th>
性别
</th>
<th>
年龄
</th>
<th>
住址
</th>
<th>
爱好
</th>
<th>
班级名称
</th>
<th>
专业方向
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@* @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })*@
</td>
<td>
@item.Name
</td>
<td>
@item.Pwd
</td>
<td>
@(item.Sex==true?"男":"女")
</td>
<td>
@item.Age
</td>
<td>
@item.Address
</td>
<td>
@item.Hobby
</td>
<td>
@item.StuName
</td>
<td>
@item.Direction
</td>
</tr>
}
</table>
</body>
</html>
no pains, no gains