What LINQ is

In this article, we will learn the following points:

  • What LINQ is
  • Why we should we use it
  • LINQ Architecture
  • LINQ Provider
  • DEMO without and with LINQ


Language Integrated Query (LINQ) enables us to query any type of data stored in SQL Server, XML documents, List, Arrays and so on.

Why we should use LINQ

Using LINQ one can work with various data sources using a similar code style without having the need to know the syntax specific to the data source.

It provides compile-time error checking and intelligence.

LINQ can be written using any .NET supported language.

LINQ Architecture

LINQ Architecture

Role of the LINQ Provider

A LINQ Provider is a component between a LINQ query and the data source that converts the LINQ query into the format that the data source can understand.

For example, the LINQ to SQL provider converts a LINQ query to T-SQL that the SQL Server database can understand.

We will discuss each of the preceding providers one by one in the future articles of this series.


Let's look at an example without using LINQ.

In SQL Server, I have a database named “db_StudentEntity” in which there is a table named “tblStudent” with five student records.


We will use the preceding table records in our console application.

In the table above, we have three different columns, in other words StudentId, StudentName and StudentGender.

So, first let’s add a new class file and name it “Student”. In that class file add three auto-implemented properties.

Add a class file as in the following:

add class

Give it the name “Student.cs”.


Click Add.

Your class will look like this.


Write the following code inside your Student class.

  1. using System;  
  2. namespace WhatIsLinq {  
  3.     class Student {  
  4.         public int StudentId { getset; }  
  5.         public string StudentName { getset; }  
  6.         public string StudentGender { getset; }  
  7.     }  
  8. }  
So, we have created our Student class and added some properties that will hold the data that we will get from the database.

The next step is to add the connection string in the app.config file.

In the ASP.NET web application, we specify the connection string in the web.config file but in the Console and Windows application, we specify the connection strings in the app.config file.
  1. <connectionStrings>  
  2.   <add name="DBCS" connectionString="server=.; database=db_studentEntity; Integrated Security=SSPI" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Where the name DBCS is a key or the index value(0) that we will retrieve the connection string in our main project using the ConfigurationManager class.

Integrated Security: Means we are using Windows authentication to connect to the SQL Server.

Integrated Security

Until now we have created our Student class and we have also specified the connection string.

The next step is to write some ADO.NET code in our main class Program.cs.

Since we are connecting to the SQL Server database. So, we will import the System.Data.SqlClient namespace.

We will also import the System.Configuration namespace because there is a class named “ConfigurationManager” that will help us in retrieving the connection string from the app.config file. But to use this class, first we need to add a reference to our project.

app config file

Select and Click OK.

In the Program.cs, create a new method whose return type will be List<Student> and in that we will write the following code:
  1. public List<Student> GetStudentDetails(){  
  2.    List<Student> studentList = new List<Student>();  
  3.           //retrieve the connection string  
  4.           string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  6.       }  

The ConnectionStrings (with an “s”) is used to get the specified string name or the index value connection string from the app.config file and the ConnectionString (without the “s”) property returns the required credentials.


The next step is to add a new SqlConnection object.
  1. public void GetStudentDetails() {            
  2.   string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  3.             //create an instance of the SqlConnection class and pass the string cs variable (which holds the connection string data) as a parameter argument in the SqlConnection constructor  
  4.             using (SqlConnection con = new SqlConnection(cs)) {  
  6.             }  
  7.         }  

If you use the using keyword then you won’t need to close the connection in the end because the connection is closed automatically when the using block is out of scope.

The next step is to create a new SQLCommand object.
  1. //create a sqlcommand object  
  2. SqlCommand cmd = new SqlCommand();  
  3. //pass the query that you want to execute using con SqlConnection  
  4. cmd.CommandText = "SELECT StudentId,StudentName, StudentGender FROM tblStudent";  
  5. cmd.Connection = con;//using this con SqlConnection object, the above query will execute.  
Then we must open the connection using the Open method.
  1. //open the connection  
  2. con.Open();  
We will invoke the ExecuteReader method that will send the command text to the SQLConnection that returns a SQLDataReader object back from where we can read all the records of the table.
  1. /*the ExecuteReader is used to when you want to retrieve data from the database and the return type of ExecuteReader() is SqlDataReader object. 
  2.  */  
  3. SqlDataReader rdr = cmd.ExecuteReader();  
The next step is to read the data and assign it to the Student properties.
  1. //it is always a good practice to read the records one by one before doing something with it and for that we can use Read() Boolean method  
  2. while (rdr.Read()) {  
  3.     //create the Student object and assign the values  
  4.     Student student = new Student();  
  5.     student.StudentId = Convert.ToInt32(rdr["StudentId"]);  
  6.     student.StudentName = (rdr["StudentName"]).ToString();  
  7.     student.StudentGender = (rdr["StudentGender"]).ToString();  
  8.     studentList.Add(student);  
  9. }  
  10. return studentList;  
Return studentList;

The entire GetStudentDetails look like this.
  1. public List<Student> GetStudentDetails() {  
  2.    List<Student> studentList = new List<Student>();  
  3.    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  5.       using (SqlConnection con = new SqlConnection(cs)) {  
  7.          SqlCommand cmd = new SqlCommand();  
  8.          cmd.CommandText = "SELECT StudentId,StudentName, StudentGender FROM tblStudent";  
  9.          cmd.Connection = con;  
  10.          con.Open();  
  11.          SqlDataReader rdr = cmd.ExecuteReader();  
  12.          while (rdr.Read()) {  
  13.             Student student = new Student();  
  14.             student.StudentId = Convert.ToInt32(rdr["StudentId"]);  
  15.             student.StudentName = (rdr["StudentName"]).ToString();  
  16.             student.StudentGender = (rdr["StudentGender"]).ToString();  
  17.             studentList.Add(student);  
  18.          }  
  19.          return studentList;  
  20.       } 
  21.    } 
  22. }  
The next step and the final step is to create an instance of our Program class in our Main method and we will invoke the GetStudentDetails() method that will return a List<Student> back and then we will loop through each Student.
  1. static void Main(string[] args) {  
  2.     Program p = new Program();  
  3.     List<Student> students = p.GetStudentDetails();  
  4.     Console.Write("Id");  
  5.     Console.Write("\t" + "\t");  
  6.     Console.Write("Name");  
  7.     Console.Write("\t" + "\t");  
  8.     Console.Write("Gender");  
  9.     Console.Write("\t" + "\t");  
  10.     Console.WriteLine();  
  11.     Console.WriteLine();  
  12.     foreach (Student s in students) {  
  13.         Console.Write(s.StudentId);  
  14.         Console.Write("\t" + "\t");  
  15.         Console.Write(s.StudentName);  
  16.         Console.Write("\t" + "\t");  
  17.         Console.Write(s.StudentGender);  
  18.         Console.WriteLine();  
  19.     }  
  20. }  
Run the application.

Run application

We have retrieved the records from the table and printed it on the console window.

But there is a problem in our application. In the following command, we don’t get any intelligence. What will happen if I change StudentId to sId?

cmd.CommandText = "SELECT StudentId,StudentName, StudentGender FROM tblStudent";

We will get an exception.


Now let’s look at the same example but this time we will use LINQ.

The first step is to add a LINQ to SQL provider in our project and for that right-click on the project then select Add -> new item.

new item

Under the visual C# item, select Data and choose LINQ to SQL classes.

LINQ to SQL classes

Click Add.

It will give you this blank window.

blank window

Click on the Server Explorer link. It will open the Server Explorer window.

Click on the marked section that will allow you to connect to the database.

connect to the database

Specify the server name and select the database.


Click OK.

You will see in the Solution Explorer that the data connection has been established.

Expand the Data Connection then expand win-db_StudentIdentity then expand Tables then select tblStudent then drag and drop it to the blank window.

drag and drop

That will provide us the following layout in the Student.dbml:


From the Solution Explorer, if you open Student.Designer.cs, you will see a partial class StudentDataContext. This class is the gateway to the database. We need to create the instance of this class in order to retrieve the data from the database.


But first remove the GetStudentDetails method from the Program.cs.

Write the following highlighted code in the main method.

Import the System.Linq namespace to write the LINQ query.
  1. class Program {  
  2. static void Main(string[] args) {  
  3.     StudentDataContext studentDataContext = new StudentDataContext();  
  4.     var students = from stud in studentDataContext.tblStudents  
  5.                    select stud;  
  6.     Program p = new Program();  
  8.     Console.Write("Id");  
  9.     Console.Write("\t" + "\t");  
  10.     Console.Write("Name");  
  11.     Console.Write("\t" + "\t");  
  12.     Console.Write("Gender");  
  13.     Console.Write("\t" + "\t");  
  14.     Console.WriteLine();  
  15.     Console.WriteLine();  
  16.     foreach (var s in students) {  
  17.         Console.Write(s.StudentId);  
  18.         Console.Write("\t" + "\t");  
  19.         Console.Write(s.StudentName);  
  20.         Console.Write("\t" + "\t");  
  21.         Console.Write(s.StudentGender);  
  22.         Console.WriteLine();  
  23.     }  
  24. }  
Run the application:

Run program

You can even retrieve data based on some conditions using the where clause and now you even get the intelligence.



  1. StudentDataContext studentDataContext = new StudentDataContext();  
  2. var students = from stud in studentDataContext.tblStudents where stud.StudentGender == "Female" select stud;  

So, we have seen how simple and easy it is to work with LINQ and what role is played by the LINQ provider.

Later articles of this series explains some important extension methods that are useful.

Until then keep learning.
Thank you