Linq Practical Info

7
Language-INte grated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. In other words LINQ has the power of querying on any source of data (Collection of ob jects, database tables or XML Files). We can easily retrieve data from any object that implements the IEnumerable<T> interface and any provider that implements the IQueryable<T> interface. Microsoft basically divides LINQ into the following three areas:   LINQ to Object : Queries performed against in-memory data  LINQ to ADO.Net o LINQ to SQL (formerly DLinq) : Queries performed against the relation database; only Microsoft SQL Server is supported.  o LINQ to DataSet : Supports queries by using ADO.NET data sets and data tables.  o LINQ to Entities : Microsoft ORM solution   LINQ to XML (formerly XLinq) : Queries performed against the XML source.  

description

Linq Practical Information Step By step

Transcript of Linq Practical Info

Language-INtegrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages. In other words LINQ has the power of querying on any source of data (Collection of objects, database tables or XML Files). We can easily retrieve data from any object that implements the IEnumerable interface and any provider that implements the IQueryable interface.

Microsoft basically divides LINQ into the following three areas: LINQ to Object : Queries performed against in-memory data LINQ to ADO.Net LINQ to SQL (formerly DLinq) : Queries performed against the relation database; only Microsoft SQL Server is supported. LINQ to DataSet : Supports queries by using ADO.NET data sets and data tables. LINQ to Entities : Microsoft ORM solution LINQ to XML (formerly XLinq) : Queries performed against the XML source.

LINQ to SQL

LINQ to SQL translates our actions to SQL and submits the changes to the database. Here we will perform Select, Insert, Update and Delete operations on a COURSE table.

Step 1:Create a COURSE Table in the database

Step 2:Create a ContextData file using the Object Relational Designer:

Create a new item, select the LINQ to SQL classes (as shown in the following figure) and name it Operation.dbml.

After clicking the Add button the ContextData file is created. Now we should drag all the tables onto the left-hand side of the designer and save (as shown in the following figure). This will create all the mappings and settings for each table and their entities.

For .dbml files the database connection string is defined in the web.config fileas:

We can use a connection string from the web.config file or we can pass a connection string as a parameter in the constructor of the DataContext class to create an object of the DataContext class.

The SELECT Operation

privatevoidGetCourses(){//create DataContext objectOperationDataContextOdContext =newOperationDataContext();varcourseTable =fromcourseinOdContext.GetTable()selectcourse;//grdCourse is gridview id grdCourse.DataSource = courseTable; grdCourse.DataBind();}

The INSERT Operation

privatevoidAddNewCourse(){//Data maping object to our databaseOperationDataContextOdContext =newOperationDataContext();COURSEobjCourse =newCOURSE(); objCourse.course_name ="B.Tech"; objCourse.course_desc ="Bachelor Of Technology"; objCourse.modified_date =DateTime.Now;//Adds an entity in a pending insert state to this System.Data.Linq.Tableand parameter is the entity which to be added OdContext.COURSEs.InsertOnSubmit(objCourse);// executes the appropriate commands to implement the changes to the database OdContext.SubmitChanges();}

The Update Operation

privatevoidUpdateCourse(){OperationDataContextOdContext =newOperationDataContext();//Get Single course which need to updateCOURSEobjCourse = OdContext.COURSEs.Single(course => course.course_name =="B.Tech");//Field which will be update objCourse.course_desc ="Bachelor of Technology";// executes the appropriate commands to implement the changes to the database OdContext.SubmitChanges();}

The DELETE Operation

privatevoidDeleteCourse(){OperationDataContextOdContext =newOperationDataContext();//Get Single course which need to DeleteCOURSEobjCourse = OdContext.COURSEs.Single(course => course.course_name =="B.Tech");//Puts an entity from this table into a pending delete state and parameter is the entity which to be deleted. OdContext.COURSEs.DeleteOnSubmit(objCourse);// executes the appropriate commands to implement the changes to the database OdContext.SubmitChanges();}

LINQ to SQL INSERT

LINQ to SQL INSERT

Before writing a LINQ to SQL query, we first need to create a DataContext using theLINQ to SQL Classes template,to know more on how to create the DataContext refer to the postLINQ 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.

INSERT into a table is a regular database operation, involved in any Transaction processing system.Assume we have the following data in the Employee and Department Tables

Table: EmployeeIDNAMEPhoneEmailDepartmentIDSalery

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

Table: DepartmentIDNAME

1Finance

2Human Resources

3IT

4Sales

5Marketing

The SQL query to insert data into the Employees table will be as follows.

INSERT INTO Employee (Name, DOB, DOJ, Phone, Email, DepartmentID, Salery)VALUES ('Robert', '10/07/1973', '05/01/2009', '111-222-3333', '[email protected]',

Now let us see how theequivalentINSERT query in LINQ Looks like.

EmployeeClassesDataContextdbContext =newEmployeeClassesDataContext();

EmployeeobjEmp =newEmployee(); objEmp.Name ="Robert"; objEmp.DOB ="10/07/1973"; objEmp.DOJ ="05/01/2009"; objEmp.Phone ="111-222-3333"; objEmp.Email ="[email protected]"; objEmp.DepartmentID = 4; objEmp.Salery = 5500;

dbContext.Employees.InsertOnSubmit(objEmp); dbContext.SubmitChanges();

After this code is executed you can find the details of the new employee in the Employees table, as follows.

IDNAMEPhoneEmailDepartmentIDSalery

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

[email protected]

LINQ to datasetTheDataSetAPI has been extented with theDataSetExtensions. They allow you to use Language-Integrated Query (LINQ) expressions against DataTable objects.The following code creates a DataTable with 3 columns and 4 rows with contact information:DataTabledt=newDataTable();dt.Columns.Add("company");dt.Columns.Add("firstname");dt.Columns.Add("name");dt.Rows.Add(newobject[]{"Facebook","Mark","Zuckerberg"});dt.Rows.Add(newobject[]{"Microsoft","Bill","Gates"});dt.Rows.Add(newobject[]{"Microsoft","Steve","Ballmer"});dt.Rows.Add(newobject[]{"Oracle","Larry","Ellison"});

A LINQ query on the DataTable is used to select all contacts wherecompanyequalsMicrosoft. This is possible after the DataTable is converted into an enumerable object using the extensions.IEnumerablequery=fromcontactindt.AsEnumerable()wherecontact.Field("company")=="Microsoft"selectcontact;

Finally, the DataRows are copied into a new DataTable using the extensionCopyToDataTable://createatablefromthequeryDataTableboundTable=query.CopyToDataTable();You can do much more with LINQ in the query. Let's say we want to order the results alphabetically by name. The keywordorderbycan be used to define the desired order:IEnumerablequery=fromcontactindt.AsEnumerable()wherecontact.Field("company")=="Microsoft"orderbycontact.Field("name")selectcontact;

This new DataTable object can be used in the Merge method of the TX Text Control MailMerge class to pass the merge data.