C#中 分层 显示数据库中多表的数据信息

时间:2023-03-09 01:48:08
C#中   分层    显示数据库中多表的数据信息

如下图,要实现将三个表中的内容加载到同一个窗体中,该怎么来实现呢?

C#中   分层    显示数据库中多表的数据信息

要实现上面的查询结果,我们就要从Student表中拿到学生姓名,从Subject表中拿到科目名称,从StudentResult表中拿到考试成绩和考试时间。

一般情况下我们都能够写出多表联查的语句来,但是今天我们所面临的不再是普通的开发,

而使用分层的原因和方法,我们在前面以及提到过,也知道了实体类中的每个类都是对应与数据库中的一张表。

那么今天我们所面临的问题是,在数据库中并没有包含(学生姓名,科目名称,考试成绩和考试时间)的一张表,

那么,我们又如何来解决这种问题呢,今天就来介绍N多中解决方案中,最简单的一种:添加扩展类。

已经学习过继承的我们,就可以在这里进行应用了。

C#中   分层    显示数据库中多表的数据信息

就像这样 ,在新添加的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,三层到此结束,目前我们所学皆为浅显的三层开发,那么在正常的开发中可能会因为业务原因,基于这三层去扩展跟多的层面。