Small exercises by yourself.
By simplifying the tedious Writing of SQL statements, LINQ to SQL makes statements more convenient and intuitive.
First, you need to create a file named "LINQ to SQL ".
Drag the created data table in the database to the LINQ to SQL file.
Create a web program and instantiate linqtosqlclassdatacontext in the program
Then begin writing the query statements of the LINQ to SQL statement.
1. Use of where
The where condition query is similar to the WHERE clause in SQL.
For example:
Linqtosqlclassdatacontext dt = new linqtosqlclassdatacontext (); Public void seat () {var query = from studentlx in DT. studentlx where studentlx. stuname = "zhangsan" select studentlx;} // search for data whose stuname is equal to that of zhangsan
View code
The preceding is a simple query method. Here, select is no different from select in SQL, but its position is changed, indicating that all values are queried.
Conditional relational query method:
// If SQL is used, select * From studentlx as St where St. stuname = "Zhang San" and St. stuage = 21
Linqtosqlclassdatacontext dt = new linqtosqlclassdatacontext (); var query = from studentlx in DT. studentlx where studentlx. stuname = "James" & studentlx. stuage = 21 select studentlx;
// Or this query method is also feasible
VaR query = DT. studentlx. Where (studentlx => studentlx. stuname = "" & studentlx. stuage = 21 );
Conditional relational query adds the conditional relational operator &, |
First () single query
First () queries are similar to top (1) in SQL statements. Only the first element is returned for queries.
For example:
// Returns the first element after successful execution.
Studentlx student = DT. studentlx. First (); // This is also feasible studentlx stud = DT. studentlx. First (studentlx => studentlx. stuname = "");
In the first format, you can use a unique value as a filter condition to determine the data that is unique.
Function compute queries (count, Min, Max, sum) extract learning from a Daniel
Public void TA () {linqtosqlclassdatacontext dt = new linqtosqlclassdatacontext (); // obtain the largest stuid // var Ss = (from studentlx in DT. studentlx select studentlx ). max (studentlx => studentlx. stuid); // var Ss = DT. studentlx. max (studentlx => studentlx. stuid); // obtain the smallest stuid // var Ss = (from studentlx in DT. studentlx select studentlx ). min (studentlx => studentlx. stuid); // var Ss = DT. studentlx. min (studentlx => studentlx. stuid); // obtain the sum of result sets // var Ss = (from studentlx in DT. studentlx select studentlx ). count (); // var Ss = DT. studentlx. count (); // obtain the sum of stuid and // var Ss = (from studentlx in DT. studentlx select studentlx ). sum (studentlx => studentlx. stuid); // var Ss = DT. studentlx. sum (studentlx => studentlx. stuid );}
It will be used later to facilitate query.
Cainiao notes-new to LINQ --- top (1)