Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » LINQ » Applications using Linq to SQL

Applications using Linq to SQL

In this article, I want to illustrate the principles, techniques and tools to develop applications using Linq to SQL after a deep research on this topic.

Author Rank:
Total page views :  3580
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Introduction

In this article, I want to illustrate the principles, techniques and tools to develop applications using Linq to SQL after a deep research on this topic.

If you look for this topic on Internet, we can see that a lot of .NET developers are blogging and discussing about this new feature of the languages in Microsoft.NET platform and its support by Visual Studio.NET 2008.

Getting to know Linq

Linq stands for Language Integrated Query and it's a new approach to access efficiently any type of data, making querying data a first class concept on .NET languages. It enables creating queries using less code, so the resulting queries are easier to understand.

It's remarkable to say that Linq is not specific to data sources, so it does not matter where the data resides. In the actual implementation, Linq is divided into four common types: Linq to Objects, Linq to DataSet, Linq to SQL, and Linq to XML. You can also extend the Linq framework to support other data source such as LDAP, SAP, etc.

Linq is part of .NET Framework 3.5; consequently we need to use Visual Studio.NET 2008 to work effectively with Linq. Microsoft has also decided to focus attention on C# when using Linq, because this language provides extensions to make working with Linq easier, although most of the techniques in Linq can be applied in Visual Basic.NET as well.

In this article, we're going to focus on Linq to SQL. Linq to SQL seamlessly maps the object model in the application to the data model in the relational data source trying to reduce the object-relational mapping mismatch. There are two main methods for the creation of required business entities and relationships associated to the data model:

  • SQLMetal, a command line tool.
  • Object relational designer, an easy to use graphical user interface.

The mechanism to access to the relational database is through the DataContext class. So, we need to create a new class derived from DataContext class, and usually this derived class has the same name than the database which contains the data model. Linq to SQL also relies on classes for specific entities such as tables. In most cases, an entity class is associated to a particular table on the database. This entity class has attributes representing the fields in the underlying table as well as for the primary and foreign keys. You can also find properties that point to a collection of child elements, so representing parent-child relationship in the database.

Getting started with Linq to SQL examples

In order to illustrate the concepts, we're going to create a Windows Forms Application, an ASP.NET Web Applications and a Class Library projects in Microsoft Visual Studio.NET 2008 to test the features of Linq to SQL technology. As the back-end, we're going to use the AdventureWorks database shipped with Microsoft SQL Server 2005/2008 as well as the Production.Product and Production.ProductSubcategory tables.

Next step is to add a Linq to SQL artifact to the Class Library by selecting the Project | Add New Item option (see Figure 1).

LinqToSql1.gif

Figure 1

Modeling the business entities

After that the Object Relational (O/R) design is launched which enables to model the classes that represent the underlying data model and the methods for each stored procedure. It will also create a strongly typed DataContext class. Unlike the DataSet/TableAdapter approach, when we're defining the entity classes in the designer, we don't have to specify the SQL queries; instead we have to focus on defining the entity classes and the mapping to the underlying data model. SQL to Linq framework will generate the appropriate SQL statements at runtime when you interact and use the business entities.

In order to create the business entities, the easy way is to open a database connection in the Server Explorer windows, select the tables and views you want to model and map from it, and drag and drop them onto the designer surface.

In this case, drag and drop the Production.Product and Production.ProductSubcategory tables on the designer surface (see Figure 2). After that you can see the business entities and their relationship.

LinqToSql2.gif

Figure 2

Linq to SQL enables modeling stored procedures as methods of the DataContext class. Let's suppose we need to return a list of a product based on a given product subcategory id (see Listing 1).

create procedure spSelectProductBySubcategory
      @pSubcategoryId int
as
begin
      select *
      from Production.Product
      where ProductSubcategoryID=@pSubcategoryId;
end;

go

Listing 1

Now we can use the Server Explorer windows to drag and drop this stored procedure on the in the right pane of the designer surface (see Figure 3).

LinqToSql3.gif

Figure 3

Executing CRUD operations

Now that we have defined our object model representing the data model, we are ready to execute CRUD (create, read, update, delete) operations over the relational data schema through the object model in C#. For example, to get the products whose makeflag is true (see Listing 2).

ProductionDataContext objDataContext = new ProductionDataContext();
var objResultset = from objProduct in objDataContext.Products
                   where objProduct.MakeFlag == true

                   select objProduct;

Listing 2

Now let's create a new product subcategory item (see Listing 3).

ProductionDataContext objDataContext = new ProductionDataContext();

ProductSubcategory objProductSubcategory = new ProductSubcategory();
objProductSubcategory.ProductSubcategoryID = 38;
objProductSubcategory.ProductCategoryID = 4;
objProductSubcategory.Name = "My new category";
objProductSubcategory.ModifiedDate = DateTime.Today;

objDataContext.ProductSubcategories.InsertOnSubmit(objProductSubcategory);

objDataContext.SubmitChanges();

Listing 3

In the following step, we're going to retrieve the newly created product subcategory (its product subcategory id is 42) and update its name field (see Listing 4).

ProductionDataContext
objDataContext = new ProductionDataContext();

var objProductSubcategory = (from objProdSubc in objDataContext.ProductSubcategories
                            where objProdSubc.ProductSubcategoryID == 42
                            select objProdSubc).First();
 
objProductSubcategory.Name = "Good product subcategory";
 
objDataContext.SubmitChanges();

Listing 4

The last CRUD operation to test is the delete operation. Now we're going to delete the created product subcategory (its product subcategory id is 42) (see Listing 5).

ProductionDataContext objDataContext = new ProductionDataContext();

var objProductSubcategory = (from objProdSubc in objDataContext.ProductSubcategories
                            where objProdSubc.ProductSubcategoryID == 42
                            select objProdSubc).First();

objDataContext.ProductSubcategories.DeleteOnSubmit(objProductSubcategory);

objDataContext.SubmitChanges();

Listing 5

Now let's call for the stored procedure defined in the Listing 1 (see Listing 6).

ProductionDataContext objDataContext = new ProductionDataContext();
var objProductSubcategory = objDataContext.spSelectProductBySubcategory(1);

Listing 6

In order to implement database paging, we need to use the Skip and Take methods (see Listing 7).
ProductionDataContext objDataContext = new ProductionDataContext();

ProductionDataContext objDataContext = new ProductionDataContext();

var objProductSubcategory = (from objProdSubc in objDataContext.ProductSubcategories
                            where objProdSubc.ProductSubcategoryID == 2

                            select objProdSubc).Skip(200).Take(10);

Listing 7

Data binding in Linq

Now let's add a Windows Form artifact to the Windows application and a DataGridView control (named m_dgvGridView) onto the form for binding purposes. Then add the following code as shown in Listing 8.

ProductionDataContext objDataContext = new ProductionDataContext();

var objResultset = from objProdSubc in objDataContext.ProductSubcategories
                   where objProdSubc.ProductCategoryID == 2
                   select objProdSubc;

this.m_dgvGridView.DataSource = objResultset;

Listing 8

When you run the application, we'll get the result as shown in Figure 4.

LinqToSql4.gif

Figure 4

Let's suppose that we want to remove the productcategoryid and rowguid columns from the result in Figure 4, so we need to re-write the query as in the Listing 9.

ProductionDataContext objDataContext = new ProductionDataContext();

var objResultset = from objProdSubc in objDataContext.ProductSubcategories
                   where objProdSubc.ProductCategoryID == 2
                   select new { objProdSubc.ProductSubcategoryID, objProdSubc.Name, objProdSubc.ModifiedDate };
 
this.m_dgvGridView.DataSource = objResultset;

Listing 9

The result is shown in Figure 5.

LinqToSql5.gif

Figure 5

Now let's work on the Web counterpart of the solution. Let's open the Default.aspx page on the Web project and add a GridView control onto the Web page (see Listing 10).

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplicationLinqTest._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <h3>Product Subcategories</h3>
        <asp:GridView ID="m_gvGridView" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>

</html>

Listing 10

Now let's add the logic to the application (see Listing 11).

ProductionDataContext objDataContext = new ProductionDataContext();

var objResultset = from objProdSubc in objDataContext.ProductSubcategories
                   where objProdSubc.ProductCategoryID == 2
                   select new { objProdSubc.ProductSubcategoryID, objProdSubc.Name, objProdSubc.ModifiedDate };

this.m_gvGridView.DataSource = objResultset;

this.m_gvGridView.DataBind();

Listing 11

The result is shown in the Figure 6.

LinqToSql6.gif

Figure 6

Executing transactions

When you execute the SubmitChanges method of the DataContext, then all the updates to the data are wrapped in a transaction, so the underlying relational database will never be in an inconsistent state after updating the changes.

If no transaction is already in the scope, then the SubmitChanges method will automatically start a database transaction. You can also define your transaction scope using the TransactionScope object. This makes very easy to integrate your transactional code with existing one.

Conclusion

In this article, I've covered the principles, techniques and tools to develop an enterprise application using Linq to SQL.


Login to add your contents and source code to this article
 About the author
 
John Charles Olamendy
He’s a senior Integration Solutions Architect and Consultant. His primary area of involvement is in Object-Oriented Analysis and Design, Database design , Enterprise Application Integration, Unified Modeling Language, Design Patterns and Software Development Process. He has knowledge and extensive experience in the development of Enterprise Applications using Microsoft.NET and J2EE technologies and standards. He is proficient with distributed systems programming; and business-process integration and messaging using the principles of the Services Oriented Architecture (SOA) and related technologies such as Microsoft BizTalk Server, Web Services (Windows Communication Foundation, WSE, BEA WebLogic, Oracle AS and Axis) through multiple implementations of loosely-coupled system. He’s a prolific blogger contributing to .NET and J2EE communities and actively writes articles on subjects relating to integration of applications, business intelligence, and enterprise applications development. He holds a Master’s degree in Business Informatics at Otto Von Guericke University, Magdeburg, Germany. He was recently awarded as MVP. He currently works in the telecommunication industry and delivers integration solutions for this industry. He harbors a true passion for the technology.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Don't start stored procedure names with 'sp' by Steve On January 16, 2010
The 'sp' stands for "System Procedure" (not 'Stored Procedure' as is commonly thought); also, SQL Server will include a search of the Master database for stored procedure names starting with 'sp', so there's also a slight performance hit.

SG
Reply | Email | Delete | Modify | 
Re: Don't start stored procedure names with 'sp' by Andrew On January 19, 2010
I made that mistake once, and then I had to go back and rename everything!  It was horrible!
Reply | Email | Delete | Modify | 
Re: Don't start stored procedure names with 'sp' by John Charles On January 25, 2010
Thanks for your insight.
My bests,
John
Reply | Email | Delete | Modify | 
Is LINQ dead? by Andrew On January 19, 2010
Rumor would have it that Microsoft has stopped development of LINQ, or is planning to do so.  Is this true?  I could never recommend LINQ to a customer if I thought Microsoft wasn't going to be supporting it five years from now.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.