Thursday, May 10, 2012

LINQ to SQL Select query with Filter (WHERE Clause)


LINQ to SQL Select query with Filter (WHERE Clause)

Before writing a LINQ to SQL query, we first need to create a DataContext using the LINQ to SQL Classes template, to know more on how to create the DataContext refer to the post LINQ to SQL Sample

Once the DataContext is created we can query the Object model using LINQ queries, let us consider the Employee table which has the following structure.




The below code will fetch the columns from the Employee Table without any filters




EmployeeClassesDataContext dbContext = new EmployeeClassesDataContext();
                       
var emp = (from e in dbContext.Employees 
          select new { e.ID, e.Name, e.Phone });


  
In many situations we will have to filter the details based on some conditions in SQL Query we can achieve this using the WHERE clause

Select ID, Name, Phone FROM Employees WHERE ID > 3

Now let us see how the same can be achieved using a LINQ query.

EmployeeClassesDataContext dbContext = new EmployeeClassesDataContext();
                       
var emp = (from e in dbContext.Employees where e.ID > 3
          select new { e.ID, e.Name, e.Phone });

Related Posts
What is LINQ?

Search Flipkart Products:
Flipkart.com

No comments: