C#实体类的关联运用

定义学生类(student):

class student
{
public string stu_id { get; set; }
public string stu_name { get; set; }
public int stu_age { get; set; }
public string stu_pwd { get; set; }
public classes cls { get; set; }
public stu_cj cj { get; set; }
}

定义班级类classes:

class classes
{
public string cls_id { get; set; }
public string cls_name { get; set; }
}

定义学生成绩类stu_cj:

class stu_cj
{
public string stu_id { get; set; }
public int cj_yw { get; set; }
public int cj_sx { get; set; }
public int cj_yy { get; set; }
}

在保存数据时:

student stud = new student();

stud.stu_name = dr["stu_name"].ToString();//直接保存


classes cls = new classes();                    //需要将其实例化
cls.cls_name = dr["cls_name"].ToString();// 保存
stud.cls = cls;         //在将其保存在学生类里面


stu_cj cj = new stu_cj();
cj.cj_yw = int.Parse(dr["yuwen"].ToString());
cj.cj_sx = int.Parse(dr["shuxue"].ToString());
cj.cj_yy = int.Parse(dr["yingyu"].ToString());
stud.cj = cj;

读取的时候则可以直接读取:

label1.Text = stu.stu_name;
label2.Text = stu.cls.cls_name;
label3.Text = stu.cj.cj_yw.ToString();
label4.Text = stu.cj.cj_sx.ToString();
label5.Text = stu.cj.cj_sx.ToString();

原文地址:https://www.cnblogs.com/ZSK991656110/p/5942801.html