There's something out there in life that will delight and amaze you.
Get up, get moving, and go find out what it is. - (Ralph Marston)

Sunday, May 18, 2008

Glimpse on LINQ TO SQL

What is Linq to SQL Server

So far all this time we have been using the ADO.NET to communicate with the Database, extracting and manipulating data. Linq to SQL opens a new window to do non other than the same thing. Linq to SQL provides ways of extracting and manipulating data on SQL Server Databases only.

How does it do it?

So, how does LINQ do it? The concept behind it is, it converts a Linq Expression to a SQL query at the backstage. But it’s not straight forward as such.

In Linq, first will look how it querys SQL data? Obviously, the DB structure should be mapped to some format understandable by linq. And that is done using the Linq to SQL class. I assume that application is already connected to some datasource.

  • Add a Linq to SQL Class to your solution; this class automatically creates necessary functionality to work with the table in the DB.
  • Open the server explores, connect to your DB and add some tables to this class; when tables are added a Linq to SQL Class which in this example the ContactDBDataContext is updated with the necessary functionality to deal with the DB.
  • Take a look at the code below.

ContactDBDataContext context = new ContactDBDataContext();
var contactData = from Course in context.Courses
                                select new { Course.Name, Course.Certification };

ContactDBDataContext is the Linq to SQL Class I added. Course is the table I added to that class. It references the course table as Courses. I’ve written a linq expression to get all the course names and certification names from the course table.

When you add your table to that class, it makes that added table identified as a System.Data.Linq.Table<TypeOfTable> and this is accessible from the Linq expression. Ok, now linq is aware of what tables to work with. Now how does it fetch the data? When linq expression is run on a Table<T> it returns an object of type System.Data.Linq.DataQuery, which has all the details to fetch the data you want. Even the SQL statement preview could be viewed by called the ‘ToString()’ on the particular DataQuery object.

This object of type System.Data.Linq.DataQuery implements the IEnumerable interface allowing it to traverse through its items using a ‘for’ loop. This object contains all the data you need to access, in this sample.

 - This is just a surface of an ocean to dive in.


At 3:04 PM, Blogger RRave said...

Hi author, it's nice post, keep on moving..


Post a Comment

<< Home