標籤:
兩張表: 班級表和學生表: 最終想獲得學生的姓名、密碼、性別、年齡、住址、愛好、班級名稱、班級所學方向
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>
asp.net mvc 遍曆linq to sql 多表聯查