需求: 上圖中,如果我們想用實體類來實現的話,明顯實現不了 原因很簡單,要顯示的數據包含的三張表(Student,Subject,Result)中的數據 我們無法單純的用某個實體類來解決,這時我們就可以擴展實體類來解決這個問題 我們可添加ResultBusiness類繼承Result實體類 這樣我們 ...
需求:
上圖中,如果我們想用實體類來實現的話,明顯實現不了
原因很簡單,要顯示的數據包含的三張表(Student,Subject,Result)中的數據
我們無法單純的用某個實體類來解決,這時我們就可以擴展實體類來解決這個問題
我們可添加ResultBusiness類繼承Result實體類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MySchool.Model { //拓展類 繼承Result實體類 public class ResultBusiness:Result { //多定義兩個屬性(達到目的) //學生姓名 public string StudentName { get; set; } //科目名 public string SubjectName { get; set; } } }
這樣我們就可以使用ResultBusiness類來實現目的
方法:
public List<ResultBusiness> ReviewStudentResult2(int subjectId, string name) { List<ResultBusiness> list = new List<ResultBusiness>(); // List<Result> list = new List<Result>(); //創建SQl StringBuilder sb = new StringBuilder(); sb.Append("select * from Result,Student,Subject where Result.StudentNo=Student.studentNo and Subject.SubjectId=Result.SubjectId "); if (subjectId != -1) { sb.Append("and Result.SubjectId=@SubjectId "); } if (!string.IsNullOrEmpty(name)) { sb.Append("and Student.StudentName like + '%'+@Studentname+'%'"); } SqlParameter[] para = { new SqlParameter("@SubjectId",subjectId), new SqlParameter("@Studentname",name) }; SqlConnection con = new SqlConnection(Constr); SqlCommand cmd = new SqlCommand(sb.ToString(), con); cmd.Parameters.AddRange(para); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { ResultBusiness result = new ResultBusiness(); result.StudentName = dr["StudentName"].ToString(); result.SubjectName = dr["SubjectName"].ToString(); result.StudentNo = Convert.ToInt32(dr["StudentNo"].ToString()); result.StudentResult = Convert.ToInt32(dr["StudentResult"].ToString()); result.SubjectId = Convert.ToInt32(dr["SubjectId"].ToString()); result.ExamDate = Convert.ToDateTime(dr["ExamDate"].ToString()); list.Add(result); } con.Close(); dr.Close(); return list; }
調用:
public void Three() { string Name = txtName.Text; int grade = Convert.ToInt32(cboGrade.SelectedValue); List<ResultBusiness> list = resultbll.ReviewStudentResult2(grade, Name); dgvResult.DataSource = list; }