Introduction To LINQ
Introduction To LINQ
What is LINQ
Benefits of using LINQ
LINQ Architecture
LINQ Providers
What is LINQ?
LINQ stands for Language Integrated Query. LINQ enables us to query any type of
data store(SQL Server documents, objects in memory etc.)
ADO.NET
SQL
Databases
XML
Documents
Arrays
Generics
LINQ enables us to work with different data sources using similar type of code style
like SQL Database, XML Documents, In-memory objects. Another benefit of using
LINQ is that it provides intellisense and compile time error checking .
For example: We are developing a Dot NET Application and this application
requires to fetch data from different data sources like Databases, XML and in
memory objects like list of customers, lists of orders, list of sales and so on. For a
developer, who is working on Dot NET Application in order to fetch data from
different data sources in order he has to understand the technology and syntax of
these different data sources. In order to fetch data from SQL he needs to
understand ADO.NET and T-SQL that is specific to SQL Database. Similarly, for XML
Documents the developer needs to understand XPATH and XSLT syntax. Also, to
fetch data from In memory objects developer needs to understand the arrays and
generics syntax and code.
LINQ Architecture:
This is the architecture for LINQ, we all know that we can develop .NET application.
Similarly, a LINQ programming returns any of the above mention .NET programming
languages. Between, the actual LINQ query and underlying data Source there is
another component called LINQ provider. The responsibility of this LINQ provider is
to convert this LINQ query into a format so that the underlying datasource can
understand.
Let say the application is trying to fetch data from SQL database if that is the case
this LINQ query will fit into the LINQ to SQL provider which is going to convert this
LINQ query into T-SQL so that the underlying database can understand.Similalrly, if
the LINQ query has to fetch data from XML Documents the same LINQ query is
going to be fed into this and which is LINQ to XML provider which is going to convert
this LINQ query into XLST so that the XML datasource can understand.
LINQ Query
Lets understand with an example
In SQL Server, we have this data
LINQ TO XML
LINQ TO SQL
LINQ TO
OBJECTS
LINQ to
ENTITIES
LINQ TO
DATASET
XML DOCS
DATABASE
OBJECT DATA
ENTITIES
DATASETS
Data Source
Providers
Now we will write some ADO.NET Code to do that create a Empty Application and
add a webform as
Now lets write the ADO.NET code for our form as:
protected void Page_Load(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
SqlCommand cmd = new SqlCommand("Select ID, FirstName, LastName, Gender from Students
where Gender='Male'", con);
List<Student> listStudents = new List<Student>();
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Student student = new Student();
student.ID = Convert.ToInt32(rdr["ID"]);
student.FirstName = rdr["FirstName"].ToString();
student.LastName = rdr["LastName"].ToString();
student.Gender = rdr["Gender"].ToString();
listStudents.Add(student);
}
con.Close();
}
}
gvData.DataSource = listStudents;
gvData.DataBind();
This is a simple ADO.NET code here ,We are reading connection string from
Web.config file using that connection string we are building SQL Connection object
and then we are passing the actual SQL command which we want executed against
SQL Database. So this is an T-SQL specific to SQL Database. Look at the query , we
have the firstname,lastname,gender from table name where gender=Male . Notice
that we dont have any form of intellisense here this query is error prone we can
make mistakes here while writing a query instead of Firstname we can commit
mistake like FirstName1 as so on . So we dont have a proper intellisense while
writing a query. Then, we are passing of List of students, opening the connection
executing list of commands and then we are looping through objects we are
creating instance of an object student and then we are retrieving data from the
reader and populating the respective properties of the student object and then
adding the student object to the list and closing the connection.
So, lets quickly run this and see whether it works or not
So, it has fetched only Male students. Now, we dont have intellisense here so lets
make some mistake and try to run the form as
We are getting this error. Since, ADO.NET queries are buried into string we dont
have intellisense or error checking. With LINQ, we do get that so we will re-write the
same example using LINQ.
Now delete the existing Webform and add another webform
Add the grid view control and lets get back to code behind file .Now we will add a
component LINQ to SQL Classes as
Right Click on the project folder -> Add -> New Item -> Data
Drag and drop the table on Sample.dbml and now go back to sample.designer.cs
file. We will understand the in detail the code in our later articles now we will write
some code in our code behind file. In addition to this in sample.designer.cs file we
have this
So what we want to do retrieve data from SQL database using a LINQ query so
whatever the LINQ query is going to return we are going to set that as datasource
for the gridview control
So we had used from keyword here and created variable student in where are the
students present now which is present in datacontext.students now we dont want
all the students we want only mail .
First, we will see for all students as
Now , lets quicly run the solution and lets see the output
Now we want to filter them we want only mail so we will apply where condition as
As you can see we got the intellisense which we were talking about earlier
We had applied where condition here as we want only Males now run the solution
As you can see from the output we had got only males now lets try to modify the
where condition we will specify the as column Gender1 and try to build our solution
As you can see from the above output its throwing an error .
So this our LINQ query now we want this query to be able to retreieve data from
underlying SQL server database.Can SQL server understand this LINQ query ? NO
SQL server can only understand T-SQL so there has to be someone in between who
is convert this LINQ query into T-SQL query to the underslying SQL database can
underatand.Who is that going to be that is nothing but the LINQ providers job LINQ
to SQL is going to convert that to T-SQL and send it to SQL Database .
To prove that we will run the solution and launch SQL server profiler and see the TSQL statement as
Now lets run the form and try to monitor the query in SQL server profiler
Now just copy that statement and paste in SQL server and run that statement you
will see the same output
Now we had seen LINQ query to work with databases now lets see an example of in
memory objects array
So here we had created array in which we want to display even numbers . So our
output will be as
Conclusion:
So, we had worked with different datasource one is T-SQL datasource and other is In
memory Datasource but the LINQ query is pretty much similar depending on
datasource its not going to change much its actual the provider who is going to
covert LINQ query into the syntax which is specific to the underlying datasource
Downloads :
You can download the complete code from here
https://code.msdn.microsoft.com/INTRODUCTION-TO-LINQ-0ae92be5