< Browse > Home / Programming / Blog article: LINQ To SQL Tutorial

| RSS

LINQ To SQL Tutorial

July 31st, 2008 | 28 Comments | Posted in Programming

Introduction

With .NET Framework 3.5 Microsoft released Language Integrated Query aka LINQ. LINQ enables developers to query data sources using a query like syntax with both C# and VB.NET. These data sources can be collections, SQL Server databases, XML, DataSets etc. Other than what is supplied by Microsoft, LINQ is also extensible. This means that you can query data sources beyond what Microsoft ships. Examples of such implementations are LINQ To Flickr, LINQ To Amazon, LINQ to Google etc. In this article I will show you how you can use LINQ To SQL to perform CRUD operations on a SQL Server database. I will use Northwind database and build an ASP.NET application to demonstrated the capabilities of LINQ To SQL. You can download Northwind database here.

Toolset for this article

  1. Visual Studio 2008
  2. .NET Framework 3.5 (This is already installed if you have Visual Studio 2008)
  3. SQL Server 2005 (You can also work with SQL Server Express)

Solution Structure

For this article we will need two projects. One is a data layer (created as a Class Library)which we will generate and the other is an ASP.NET Web Application. The solutions structure looks like this in Solution Explorer.

LINQ

Creating Data Layer

Before we generate our data layer we must create a new connection in Server Explorer which points to Northwind database.

LINQ

We will now generate our data layer using LINQ To SQL. To do this you need to add a new item to the data layer project of type LINQ to SQL Classes. We will name it Northwind as shown below.

LINQ

After adding a LINQ to SQL Class we are presented with a designer surface. Here we can simply drag the tables which will become part of our data layer. For this article we will drag all tables on the designer by selecting them all in one go. Our designer should look like this after dragging all tables on it.

LINQ

We should now build our solution to make sure everything is okay. And that’s it. We have successfully generated our data layer. In Solution Explorer we can see that we have two new files namely Northwind.dbml.layout and Northwind.designer.cs. We can also see that references required to compile and run our code have been added by Visual Studio.

LINQ

The .cs file contains the code for our data layer. Let’s examine the code that has been generated for us. We will look at the Region class.

[Table(Name="dbo.Region")]
public partial class Region : INotifyPropertyChanging, INotifyPropertyChanged

The class itself is decorated with Table attribute and the Name property has been assigned the actual table name we have in our database. Region class also implements INotifyPropertyChanging and INotifyPropertyChanged interfaces. These interfaces are used for databinding. Region class also contains one property per column. Let’s look at the RegionDescription property.

[Column(Storage="_RegionDescription", DbType="NChar(50) NOT NULL",
CanBeNull=false)]
public string RegionDescription
{
  get
  {
    return this._RegionDescription;
  }
  set
  {
    if ((this._RegionDescription != value))
    {
      this.OnRegionDescriptionChanging(value);
      this.SendPropertyChanging();
      this._RegionDescription = value;
      this.SendPropertyChanged("RegionDescription");
      this.OnRegionDescriptionChanged();
    }
  }
}

Columns are decorated with Column attribute and values are passed in for Storage, DbType and CanBeNull which indicates if the column can be null or not.

Using Data Layer

Now that we have generated our data layer. We will work on ASP.NET web application where we will use our data layer. To keep things simple we will create a web forms to search for customers and display search results. We will also create a web form to insert new customers. Let’s start by creating our web form for customer search. For this we will use the Default.aspx page. We will place few controls on the web form. These controls will give us search parameters and a button which will do the search and display results when clicked. This is what the form will look like after placing our controls.

LINQ

We will also place a GridView control on our form to display search results. We will now put in some code in our button’s click event handler to do the search and display results in GridView. Make sure that we have a reference to Data Layer project, System.Data.Linq and appropriate using statement. Here is what our button click event handler will contain.

protected void buttonSearch_Click(object sender, EventArgs e)
{
  using (NorthwindDataContext context = new NorthwindDataContext())
  {
    var customers =
      from c in context.Customers
      select c;
    gridViewCustomers.DataSource = customers;
    gridViewCustomers.DataBind();
  }
}

This code will query the customers table in northwind database and will return all customers. We will now modify it slightly to accept customer name and company name as parameters for our query. After modification our event handler looks like this.

protected void buttonSearch_Click(object sender, EventArgs e)
{
  using (NorthwindDataContext context = new NorthwindDataContext())
  {
    var customers =
      from c in context.Customers
      where (
        c.ContactName.Contains(textBoxCustomerName.Text.Trim())
        &&
        c.CompanyName.Contains(textBoxCompanyName.Text.Trim()))
      select c;
      gridViewCustomers.DataSource = customers;
      gridViewCustomers.DataBind();
  }
}

Our search results will now be filtered.

Let us now created a data entry form for customers.  We will insert a new web form in our ASP.NET project and call it CustomerEntry. To start with we will make sure that our form contains fields required to insert a customer. Our form after completion will look like this.

LINQ

We expect a new row to be inserted into customers table when Save Customer button is clicked. This code achieves data insertion into customers table for us.

protected void buttonSave_Click(object sender, EventArgs e)
{
  using (NorthwindDataContext context = new NorthwindDataContext())
  {
    Customer customer = new Customer
    {
      CustomerID = textBoxCustomerID.Text,
      CompanyName = textBoxCompanyName.Text,
      ContactName = textBoxCustomerName.Text,
      ContactTitle = textBoxTitle.Text,
      Address = textBoxAddress.Text,
      City = textBoxCity.Text,
      Region = textBoxRegion.Text,
      PostalCode = textBoxPostalCode.Text,
      Country = textBoxCountry.Text,
      Phone = textBoxPhone.Text,
      Fax = textBoxFax.Text
    };
    context.Customers.InsertOnSubmit(customer);
    context.SubmitChanges();
  }
}

Similarly an existing row in database can be updated by first retrieving the data and then submitting it via DataContext.

Conclusion

In this tutorial we have not written a single SQL statement to retrieve or insert data into a database. This is the beauty of LINQ To SQL. Further our retrieval code while in C# looks a lot like a query. We can already appreciate the benefits of such a streamlined and unified approach in dealing with data.

Technorati Tags:

kick it on DotNetKicks.com






Leave a Reply 21652 views, 105 so far today |
Tags:
Follow Discussion

28 Responses to “LINQ To SQL Tutorial”

  1. ahmad Says:

    hi
    it’s Wery Good .
    thanks

  2. Deepak Says:

    Ahmad,
    Thanks for kind words.

  3. Mohammed Says:

    Deepak:

    Your explanation is awesome, you’ve done a great job in explaining a complex topic with such ease. I’ll be looking forward for more from you.

    Thanks!

    Mohammed

  4. Deepak Says:

    Hi Mohammed,

    Thanks for encouraging comment. Comments such as yours are very motivating.

    Thanks again.

  5. Sachith Says:

    nice article.
    Thanks.

  6. Deepak Says:

    Thankyou Sachith.

  7. Brent V Says:

    This was clear and really helped. Thank you!

    Brent

  8. Deepak Says:

    Thanks Brent. I’m glad that you found the article useful.

  9. Rajasekar Says:

    Thank you. Its much clear!

  10. Deepak Says:

    Rajasekar, Thanks for kind words.

  11. Rohan Dave Says:

    Hi,
    It’s really a very nice example.I just want to know something regarding O/R designer.Is there any way to add tables without using O/R designer?
    I mean to say after adding LINQ to SQL class, can we add tables form Server Explorer to design surface dynamically? Is there any method exist to do this? like Add() method.
    Kindly let me know , I am waiting for your replay.

  12. Deepak Says:

    Hi Rohan,

    You can use SQLMetal tool to generate LINQ To SQL entities. SQLMetal does not need a designer as it is a command line utility.

    SQLMetal is shipped with Windows SDK. Once you have installed the SDK you can find SQLMetal at C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\SqlMetal.exe

  13. M.Nabil Says:

    This helped me too much.thanks alot for those who published that and I hope to see more..THANKS

  14. Rohan Dave Says:

    Hey Deepak,

    Thanks for information and quick response :-).Can you please let me know how to use this SQLMetal.exe ? do we need to use this in the C# IDE or something else? Actually I haven’t used this so confused.

    Thanks

  15. Deepak Says:

    Hi Rohan,

    You do not need C# IDE to run SQLMetal. Ben Hall wrote an excellent post on SQLMetal which shows you different ways the tool can be used. Here is the link http://blog.benhall.me.uk/2007/08/power-of-sqlmetal.html

  16. Rohan Dave Says:

    Hi Deepak,

    Thank you very much.I have taken a look on your given web link and it’s really amazing.I can learn lots of things from this.Again thanks a lot for your help.I want to register myself on this onedotnetway site.Does site has this facility ?

  17. Deepak Says:

    Hi Rohan,

    I’m glad that you found the information helpful. You can subscribe to One .Net Way feed http://feeds2.feedburner.com/OneDotNetWay

    Or

    Get daily updates by email. Go to “Connect with me” orange box on this page (about half way up) and enter your emaill address and hit subscribe.

  18. Rohan Dave Says:

    Hey Deepak,
    what’s up? I have one question in my mind regarding LINQ to SQL. is there any properties or method supported by LINQ to SQL which returns SQL query itself during debug the code? I mean to say whether we can retrieve SQL query itslef using LINQ code in the C#.net or not.
    Waiting for your replay :-)
    hey dude are you in LinkedIn :-)

  19. Deepak Says:

    Hi Rohan,

    There are few ways to capture the query generated by LINQ To SQL. I wrote a post about it some time ago. Here is the link:

    http://www.onedotnetway.com/view-query-generate-by-linq-to-sql/

    Yes I am on Linked In. Here are links to me on Social Networks:

    Linked In: http://www.linkedin.com/in/kapoordeepak
    Facebook: http://www.facebook.com/people/Deepak-Kapoor/625431493
    Twitter: http://twitter.com/deepakkapoor

    Hope to see on some of them soon.

  20. Sanhita Says:

    Brilliant……pls cover as much topic as you can…..its really an asset….

  21. Deepak Says:

    Thank you Sanhita.

  22. Rohan Says:

    Thank you very much Deepak. yes you will see me on linkedin soon
    thanks again

  23. ihtesham Says:

    Hi

    Thanks for this info but have you any ideas on how to implement Linq to sql in a 3 layered application model. I am struggling with that.

    Thanks in advance

  24. Balaji Birajdar Says:

    Brilliant. This post was exremely helpful to me. Thanks a lot. Keep up the good work

  25. Deepak Says:

    Balaji,

    Thanks for your encouraging comment. I’ll try my best to keep up :)

  26. sandesh Says:

    thanks
    its very usefull

Trackbacks

  1. Different Flavors Of LINQ | One .Net Way  
  2. LINQ Equivalent Of Where IN | One .Net Way  

Leave a Reply