C # simple use of Linq

Source: Internet
Author: User

1. student is a table in the database. The student ID (stu) and name (xingming) are two fields in the table, and the student ID is the primary key.

In the Page_Load event of the page, query the data in the table through 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 +"
");
}
}

On the page, add data to the database through 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 ();
// Refresh the data
Table List = context. GetTable ();
Var query = from student in list select student;
Foreach (var student in query)
{
Response. Write (student. xuehao + "," + student. xingming +"
");
}
}

Modify data through 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 ();
}

Delete data through 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 ();
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.