mainEntities2 dbcontext = new mainEntities2(); private void btnAdd_Click(object sender, RoutedEventArgs e) { Students stu = new Students(); stu.StudentName_ = "李四"; stu.StudentSex_ = "男"; stu.StudentAge_ = 19; stu.StudentProvince_ = "上海"; stu.StudentPhone_ = "17468523001"; dbcontext.Entry<Students>(stu).State = System.Data.Entity.EntityState.Added; int i = dbcontext.SaveChanges(); string str = i == 1 ? "添加成功" : "添加失败"; MessageBox.Show(str); } private void btnDel_Click(object sender, RoutedEventArgs e) { Students stu = new Students(); stu.StudentNO_ = 1; dbcontext.Entry<Students>(stu).State = System.Data.Entity.EntityState.Deleted; int i = dbcontext.SaveChanges(); string str = i == 1 ? "删除成功" : "删除失败"; MessageBox.Show(str); } private void btnUpdate_Click(object sender, RoutedEventArgs e) { //修改整个 //Students stu = new Students(); //stu.StudentNO_ = 2; //stu.StudentName_ = "李四"; //stu.StudentSex_ = "男"; //stu.StudentAge_ = 19; //stu.StudentProvince_ = "上海"; //stu.StudentPhone_ = "17468523001"; //dbcontext.Entry<Students>(stu).State = System.Data.Entity.EntityState.Added; //int i = dbcontext.SaveChanges(); //string str = i == 1 ? "修改成功" : "修改失败"; //MessageBox.Show(str); //修改某个属性 Students stu = new Students(); stu.StudentNO_ = 2; stu.StudentName_ = "王霸26"; dbcontext.Students.Attach(stu);//必须使用attach //dbcontext.Entry<Students>(stu).Property<string>(s => s.StudentName_).IsModified = true; dbcontext.Entry<Students>(stu).Property("StudentName_").IsModified = true; int i = dbcontext.SaveChanges(); string str = i == 1 ? "修改成功" : "修改失败"; MessageBox.Show(str); } private void btnSelect_Click(object sender, RoutedEventArgs e) { //便利所有 foreach (var item in dbcontext.Students) { Console.WriteLine($"学号:{item.StudentNO_} 姓名:{item.StudentName_}"); } //查询整个表女生的信息 var temp = from s in dbcontext.Students where s.StudentSex_ == "女" select s; foreach (var item in temp) { Console.WriteLine($"学号:{item.StudentNO_} 姓名:{item.StudentName_} 性别:{item.StudentSex_}"); } }