Friday 18 October 2013

How to join two table using LINQ (Language Integrated Query)


In this articel i will explain what is LINQ? what are the advantages and disadvantages with examples 

What Is LINQ

Language-Integrated Query (LINQ) is a set of features introduced in Visual Studio 2008 that extends powerful query capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned patterns for querying and updating data, and the technology can be extended to support potentially any kind of data store. Visual Studio includes LINQ provider assemblies that enable the use of LINQ with .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.


Advantages of LINQ

Debugging

As debug point concern, as LINQ is a part of .NET, we can use the visual studio’s debugger to debug the queries but is tough to debug the stored procedure as it will not support the visual studio debugger.

Deployment

In case of deployment, we need to provide an additional script for stored procedures to execute but in case of LINQ, it will compile into single DLL hence deployment becomes easier.

Type Safety

As LINQ is type safe, the queries errors are type checked at compile time. Better suggest using LINQ because it helps to encounter an error at the compile time rather than at runtime exception.

Disadvantages of LINQ

It is not precompiled statement whereas stored procedures are precompiled. In case of LINQ the queries need to be complied before the execution.

Now we will see how we will join two tables using LINQ

First declare a variable

var JoinTable;

We will declare an object to the database model.

DataBaseModel objDataBaseModel=new DataBaseModel ();

Now we will select the desired table from the database object.

from c in objDataBaseModel.tblTable1

Now create another object, for example emp

The join operation is performed on the tables which have at least one similar column.

In LINQ we will use equals in place of join.

Now the entire join statement is

var JoinTable=(from c in objDataBaseModel.tblTable1 join emp in objDataBaseModel.tblTable2 on c.tblTable1ID equals emp.tblTable2ID select c).FirstOrDefault();

No comments:

Post a Comment