Social Icons

Pages

Sunday, May 18, 2014

LINQ

It stands for Language Integrated Query. LINQ is a set of features introduced in Visual Studio 2008 that provides the query facilities into .NET framework language like C#, VB.NET.

Basic LINQ Queries 
public class DALEmployee
    {
       //creating the datacontext instance
       DbConnectionDataContext data = new DbConnectionDataContext();

       //**Retrieve data using LINQ Query**
       public List<tbl_Employee> GetAllEmployees()
       {
           var empdata = from emp in data.tbl_Employees
                         orderby emp.EmployeeID descending
                         select emp;

           return empdata.ToList<tbl_Employee>();
       }

       //**Where Condition in LINQ Query**
       public List<tbl_Employee> GetEmployeebyID(int EmployeeID)
       {
           var empdata = from emp in data.tbl_Employees
                         where emp.EmployeeID == EmployeeID
                         select emp;

           return empdata.ToList();
       }

       //**Insert Data using LINQ Query**
       public int InsertData(tbl_Employee employee)
       {
           data.tbl_Employees.InsertOnSubmit(employee);
           data.SubmitChanges();
           return employee.EmployeeID;
       }
       //**Update Data using LINQ Query**
       public int UpdateData(tbl_Employee employee)
       {
           tbl_Employee objEmployee = data.tbl_Employees.Single(course => course.EmployeeID == employee.EmployeeID);
           objEmployee.Telephone= employee.Telephone;
           objEmployee.Address2 = employee.Address2;
           data.SubmitChanges();
           return employee.EmployeeID;
       }
       //**Delete Data using LINQ Query**
       public bool DeleteData(int employeeID)
       {
           tbl_Employee objEmployee = data.tbl_Employees.Single(course => course.EmployeeID == employeeID);
           data.tbl_Employees.DeleteOnSubmit(objEmployee);
           data.SubmitChanges();
           return true;
       }

       //**Retrieve data using SP**
       public void GetdatausingSP(int EmployeeID)
       {
           var returndata = (from c in data.SP_GetEmployeeData(1)
                             select new tbl_Employee
                             {
                                FirstName  = c.FirstName,
                                LastName=c.LastName
                             }).ToList<tbl_Employee>();
       }
      
    }

References:
http://msdn.microsoft.com/en-us/library/bb397926.aspx

Interview Questions and Answers:
http://aspnet-jitendra.blogspot.sg/2013/07/linq-interview-questions-and-answers.html

No comments:

Post a Comment