日期:2014-05-20 浏览次数:20937 次
1.student是数据库中的一张表,学号(stu)和姓名(xingming)是表中的两个字段,学号是主键。
在页面的Page_Load事件中通过Linq查询表中的数据:
protected void Page_Load(object sender, EventArgs e)
{
StudentDataClassesDataContext context = new StudentDataClassesDataContext();
Table<student> list = context.GetTable<student>();
var query = from student in list select student;
foreach (var student in query)
{
Response.Write(student.xuehao+","+student.xingming+"<br>");
}
}
在页面中通过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<student> list = context.GetTable<student>();
var query = from student in list select student;
foreach (var student in query)
{
Response.Write(student.xuehao + "," + student.xingming + "<br>");
}
}
通过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();
}