1.student是數據庫中的一張表,學號(stu)和姓名(xingming)是表中的兩個字段,學號是主鍵。
在頁面的Page_Load事件中通過Linq查詢表中的數據:
protected void Page_Load(object sender, EventArgs e)
{
StudentDataClassesDataContext context = new StudentDataClassesDataContext();
Table
var query = from student in list select student;
foreach (var student in query)
{
Response.Write(student.xuehao+","+student.xingming+"
");
}
}
在頁面中通過Linq在數據庫中添加數據:
protected void btn_Add_Click(object sender, EventArgs e)
{
student stu = new student();
stu.xuehao = txt_XueHao.Text;
stu.xingming = txt_XingMing.Text;
StudentDataClassesDataContext context = new StudentDataClassesDataContext();
context.student.InsertOnSubmit(stu);
context.SubmitChanges();
//重新刷新數據
Table
var query = from student in list select student;
foreach (var student in query)
{
Response.Write(student.xuehao + "," + student.xingming + "
");
}
}
通過Linq修改數據:
protected void btn_Modify_Click(object sender, EventArgs e)
{
StudentDataClassesDataContext context = new StudentDataClassesDataContext();
var query = from student in context.student where student.xuehao == "001" select student;
foreach (var student in query)
{
student.xingming = "宋學習";
}
context.SubmitChanges();
}
通過Linq刪除數據:
protected void btn_Delete_Click(object sender, EventArgs e)
{
StudentDataClassesDataContext context = new StudentDataClassesDataContext();
var query=from student in context.student where student.xuehao=="001" select student;
foreach (var student in query)
{
context.student.DeleteOnSubmit(student);
}
context.SubmitChanges();
}