Follow us

Monday, December 5, 2011

LINQ to SQL #1 : An Introduction

LINQ is a quering programming model which stands for .NET Language Integrated Query. Developers can express efficient query behavior in their programming language of choice, optionally transform/shape data query results into whatever format they want, and then easily manipulate the results.


LINQ to SQL is an O/RM (Object-Relational mapping) implementation that ships in the .NET Framework "Orcas" release.

LINQ to SQL allows you to model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it.

Key Features of LINQ to SQL

  • Fully supports transactions, views, and stored procedures.
  • Provides an easy way to integrate data validation and business logic rules into your data model.

Modelling Database using LINQ to SQL

Visual Studio "Orcas" ships with a LINQ to SQL designer (Object Relational designer) that provides an easy way to model and visualize a database as a LINQ to SQL object model. Using the LINQ to SQL designer, we can easily create a representation of the sample "Technoscatter" database like below:

LINQ to SQL design Surface

There are two entity classes:

  1. Organisation
  2. Member

The properties of each class map to the columns of a corresponding table in the database. Each instance of a class entity represents a row within the database table.

The arrows between these two entity classes above represent associations/relationships between them. These are typically modeled using primary-key/foreign-key relationships in the database.

The direction of the arrows on the design-surface indicate whether the association is a one-to-one or one-to-many relationship. Strongly-typed properties will be added to the entity classes based on this.

The right-hand method pane within the LINQ to SQL design-surface above contains a list of stored procedures that interact with our database model. In the sample above, there are two Stored Procdures.

  1. AddAndUpdateMembershipDetails
  2. CheckIfOrganisationExists

DataContext Class

When you press the "save" button within the LINQ to SQL designer surface, Visual Studio will persist out .NET classes that represent the entities and database relationships that we modeled. For each LINQ to SQL designer file added to our solution, a custom DataContext class will also be generated. This DataContext class is the main conduit(passage) by which we'll query entities from the database as well as apply changes.

The DataContext class created will have:

  • Properties that represent each Table we modeled within the database, and
  • Methods for each Stored Procedure we added.

Hope! this will be helpful to all LINQ to SQL Begineers.

Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "LINQ to SQL #1 : An Introduction"

Post a Comment