Gary Devenay

Web Development

Basics of ASP.NET linq C#

July21

Until now data access has been a tedious task, creating data, entity and service layers grows old after the 400th time. Even when using NHibernate this task can chew up the majority of your development time.

In the .NET 3.5 framework Microsoft have developed a new form of data access, somthing that can free us from our masses of SQL and service layers. Linq.

Linq is a language that resembles SQL script to and immitates SQL script (so your thinking “then isn’t it SQL?”) but there is one major difference… It’s written in C# (or VB if you choose)!

By using linq you completely eleminate stored procedures and data layers and keep one little layer to keep your methods nice and tidy.

Not only can linq be used to access data in a database. It can be used to access XML, Datasets and anything that inherits the IEnumerable interface. Using the IEnumberable is the most basic way of using linq to manipulate data as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System;
using System.Collection.Generic;
using System.Linq;
using System.Text;
 
public static QueryOverStrings()
{
string[] list = {   "Crysis", "Call Of Duty: Modern Warefare", "Halo 3", "Sonic", "Bioshock 2" };
 
var subset = from games in list
where games.Contains("C");
orderby games
select games;
 
foreach (var  s in subset)
Response.Write("Item: {0}", s);
}
 
public static Page_Load(object sender, EventArgs e)
{
QueryOverStrings();
}

This should return a list that looks like this:

1
2
3
4
Item: Crysis
Item: Call Of Duty: Modern Warefare
Item: Sonic
Item: Bioshock 2

The method above shows how a simple few lines of linq can select all items from within an array that cotains the letter “C”. This shows how simple data access can become by using linq.

Further will be posted on linq as my knowledge progresses.

posted under ASP.NET

Email will not be published

Website example

Your Comment: