程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# Linq的簡單使用

C# Linq的簡單使用

編輯:C#入門知識

1.student是數據庫中的一張表,學號(stu)和姓名(xingming)是表中的兩個字段,學號是主鍵。

在頁面的Page_Load事件中通過Linq查詢表中的數據:

protected void Page_Load(object sender, EventArgs e)
{
StudentDataClassesDataContext context = new StudentDataClassesDataContext();
Table list = context.GetTable();
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 list = context.GetTable();
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();
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved