Wednesday, May 9, 2012

LINQ to SQL Select Query with Specific columns


LINQ to SQL Select Query with Specific columns

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 all the columns from the Employee Table

EmployeeClassesDataContext dbContext = new EmployeeClassesDataContext();

var emp = from employees in dbContext.Employees select employees;

grdEmployees.DataSource = emp;
grdEmployees.DataBind();


Now we will select only the columns ID, Name and Phone and the Query for this will be as follows.

EmployeeClassesDataContext dbContext = new EmployeeClassesDataContext();

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

grdEmployees.DataSource = emp;
grdEmployees.DataBind();

Related Posts

Search Flipkart Products:
Flipkart.com

No comments: