Wednesday, June 3, 2009

LINQ Data Sources - Part I

There is a huge buzz involved about LINQ post .NET Framework 3.5 release. I have shared some useful information on using LINQ(Language-Integrated Query) data sources.


1. LINQ gives a set of query operators that are available as C# Keywords. Those keywords will be used to denote/define an expression ie. Query Expression that retrieves tha data you want.

2. Source data for a query must implement IEnumerable interface or interface that implements IEnumerable like IQueryable

3. Datasource of LINQ can be array or an array list that supports non-generic IEnumerable interface.

Example of LINQ to Objects(LINQ Implementation)

LINQ query that retrieves key values from a sorted list

Mark List

SortedList markList = new SortedList();
markList.Add("Karthick", 80);

so the query expression to select the names from the list:

var nameList= from names in markList
select names.Key;

To execute the query the code is:

string strName=string.Empty;
foreach (var name in nameList)
strName+= name + "\n";
MessageBox.Show(strName,"Names from the list");

Important C# keywords for LINQ:

from -> Retrieves source of data for a query
where -> Tells which elements are retrieved from the data source
orderby ->For sorting
select -> Return contents
group -> Group by (aggregate on groups).
join -> Connecting data from two data sources

Using LINQ with SQL Server

Step 1: Object model creation that maps to the data model of the database.
Step 2: Query definition
Steo 3: Query Execution


Code to use LINQ to query the EmployeeDetails table in EmployeeList database

EmployeeList db=new EmployeeList();

var employees=from employee in db.EmployeeDetails
where employee.Age >25
orderby employee.EmployeeID
select new


GridView1.DataSource =employees;

Object Model provides a measure as a link between objects used by application and objects in a relational database. Object model can be written in C#.

i. Object Relational Designer can be used to create object model.

ii. Implementation of LINQ to work with relational DB is called as LINQ to SQL.(Till date LINQ to SQL can be used with only SQL Server DB).

iii. LINQ to SQL can insert, update, delete and select data.

Use of Object Relational Designer will be shared in Part-II.

No comments: