/// <summary> /// 添加新学生 /// </summary> /// <param name="model">要添加的学生</param> /// <returns>成功返回true</returns> public static bool AddStudent(Student model) { try { using (var db = new SEMSDBContext()) { db.Student.Add(model); db.SaveChanges(); } return true; } catch// (Exception ee) { //throw ee.InnerException; return false; } }
/// <summary> /// 修改学生信息 /// </summary> /// <param name="class_id">学号</param> /// <param name="model">修改后的学生信息</param> /// <returns>成功返回true</returns> public static bool ModifyStudent(string student_id, Student model) { try { using (var db = new SEMSDBContext()) { Student temp = db.Student.Find(student_id); //db.Student.Attach(temp); temp.student_name = model.student_name; temp.student_sex = model.student_sex; temp.class_id = model.class_id; temp.class_small_id = model.class_small_id; db.SaveChanges(); } return true; } catch { return false; } }
/// <summary> /// 从Excel批量导入学生信息 /// 说明:必须是“Sheet1”,必须有姓名、学号、性别列。 /// </summary> /// <returns>成功添加或修改的学生个数,若出错返回-1</returns> public static int ImportStudent(string class_id, string class_small_id, string fileName) { try { int ret = 0; using (var db = new SEMSDBContext()) { //string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=YES;IMEX=1'Data Source=" + fileName + ";"; //HDR=Yes,代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES。IMEX=1,表示只读 string strConn = "Provider=Microsoft.ACE.OLEDB.12.0; Persist Security Info=False;Data Source=" + fileName + "; Extended Properties='Excel 12.0;HDR=Yes;IMEX=1'"; using (OleDbConnection conn = new OleDbConnection(strConn)) { try { conn.Open(); string sql = "select * from [Sheet1$]"; OleDbCommand cmd = new OleDbCommand(sql, conn); OleDbDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { Student student = new Student() { student_name = dr["姓名"].ToString(), student_id = dr["学号"].ToString(), student_sex = dr["性别"].ToString(), class_id = class_id, class_small_id = class_small_id }; if (StudentBS.AddStudent(student)) { ret++; } else if (StudentBS.ModifyStudent(student.student_id, student)) { ret++; } } } catch (Exception e) { throw e; } finally { conn.Close(); } } } return ret; } catch { return -1; } }
public static void TestStuAdd(Student model) { StudentBS.AddStudent(model); }