标签:
需求:
上图中,如果我们想用实体类来实现的话,明显实现不了
原因很简单,要显示的数据包含的三张表(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; }
标签:
原文地址:http://www.cnblogs.com/zhangzongle/p/5334042.html