如下圖,要實現將三個表中的內容加載到同一個窗體中,該怎么來實現呢?

要實現上面的查詢結果,我們就要從Student表中拿到學生姓名,從Subject表中拿到科目名稱,從StudentResult表中拿到考試成績和考試時間。
一般情況下我們都能夠寫出多表聯查的語句來,但是今天我們所面臨的不再是普通的開發,
而使用分層的原因和方法,我們在前面以及提到過,也知道了實體類中的每個類都是對應與數據庫中的一張表。
那么今天我們所面臨的問題是,在數據庫中並沒有包含(學生姓名,科目名稱,考試成績和考試時間)的一張表,
那么,我們又如何來解決這種問題呢,今天就來介紹N多中解決方案中,最簡單的一種:添加擴展類。
已經學習過繼承的我們,就可以在這里進行應用了。

就像這樣 ,在新添加的StudentExtens類中就可以添加擴展的字段了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Combox.Model
{
public class StudentExtens:Student
{
public string SubjectName { get; set; }
public int StudentResult { get; set; }
public DateTime ExamDate { get; set; }
}
}
這樣,我們就可以在DAL層來實現查詢相應的數據了
//查看學生成績信息 public List<StudentExtens> SelectStudentResult() { List<StudentExtens> list = new List<StudentExtens>(); SqlConnection con = new SqlConnection("Server=192.168.100.100;initial catalog=MySchool;uid=sa;pwd=1"); DataTable dt = SQLHelper.ExecuteDataTable(@"select studentname,subjectname,studentresult,examdate from student,subject,result where student.studentno=result.studentno and result.subjectid=subject.subjectid"); foreach (DataRow item in dt.Rows) { StudentExtens se = new StudentExtens(); se.StudentName = item["studentname"].ToString(); se.SubjectName = item["subjectname"].ToString(); se.StudentResult = Convert.ToInt32(item["studentresult"]); se.ExamDate = Convert.ToDateTime(item["examdate"]); list.Add(se); } return list; }
在BLL層中
using Combox.DAL;
using Combox.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Combox.BLL
{
public class StudentBLL
{
StudentDAL dal = new StudentDAL();
public List<StudentExtens> SelectStudentResult()
{
return dal.SelectStudentResult();
}
}
}
在UI層中就可以進行調用了
//加載所有的dgvList
StudentBLL bll = new StudentBLL();
List<StudentExtens> list = bll.SelectStudentResult();
dataGridView1.DataSource = list;
ok,三層到此結束,目前我們所學皆為淺顯的三層開發,那么在正常的開發中可能會因為業務原因,基於這三層去擴展跟多的層面。
