Getting started with LINQ

24 בספטמבר 2007

תגובה אחת

Language Integrated Query (LINQ) introducing a standard set of operators that can be used to query several different data stores such as SQL Server and XML. LINQ comes as part of the future revisions of both the C# and VB.NET compilers (VS 2008).

LINQ architecture

As we see at the figure below, the data to be queried can take the form of XML (LINQ to XML), databases (LINQ-enabled ADO.NET, which includes LINQ to SQL, LINQ to Dataset and LINQ to Entities), objects (LINQ to Objects), and so on.

(Click to enlarge every image)

Architecture

Each middle tier component provides us with the required functionality to interact with that component’s data store.

 

First application

This application help us with core understanding of how a query is constructed and what types of collections you can query.

   1:          static void Main(string[] args)
   2:          {
   3:              string[] bloggers = { "Maor", "Leon", "Guy", "Mr. Elimelech"};
   4:   
   5:              IEnumerable<string> query = from b in bloggers
   6:                                          where b.StartsWith("M")
   7:                                          select b;
   8:   
   9:              foreach (string blogger in query)
  10:              {
  11:                  Console.WriteLine(blogger);
  12:              }
  13:   
  14:              Console.ReadLine();
  15:          }

In this snippet we use several standard operators to construct a query which filters out all blogger which start with the letter ‘M’, however, of more significant importance is the collection which we have queried.

We can query any in-memory collection which implements IEnumerable, or IEnumerable<T>.

If we run this example in debug mode, placing a breakpoint on the same line as the foreach statement, we can see that the compiler is doing some extra work for us under the covers:

1

An implementation detail of the query given above is that we are actually creating a lambda expression when the code is compiled, this expression is used as a parameter for the Where() extension method of the bloggers collection.

Linq to SQL

LINQ to SQL is an O/RM (object relational mapping) implementation. 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.

In my example, I'll use the Northwind database. I created a representation of the database like below. I can do it by SqlMetal or by adding Linq to Sql classes and drag the objects I want from the server explorer to the designer.

Northwind

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 DataContext: I pressed the "save" button within the LINQ to SQL designer surface and Visual Studio generated .NET classes that represent the entities and database relationships that we modeled. Every LINQ to SQL designer file has a custom DataContext class which also generated.  This DataContext class is the main conduit 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, as well as methods for each Stored Procedure we added.

 

Query the database

The code below query the database against customers which company name is 'Cactus Comidas para llevar'.

   1:  Northwind db = new Northwind();
   2:  var customers = from c in db.Customers
   3:                  where c.CompanyName == "Cactus Comidas para llevar"
   4:                  select c;

 

Insert new data

This code demonstrate how to insert new customer to customers table:

   1:  Northwind db = new Northwind();
   2:  Customer cust = new Customer();
   3:  cust.CustomerID = "MDP";
   4:  cust.CompanyName = "Maor David Ltd.";
   5:   
   6:  db.Customers.Add(cust);
   7:  db.SubmitChanges();

 

Updating data

Demonstration how to retrieve a single customer from the database, update its country, and then save the changes back to the database.

   1:  Northwind db = new Northwind();
   2:  var customers = from c in db.Customers
   3:                  where c.CompanyName == "Cactus Comidas para llevar"
   4:                  select c;
   5:   
   6:  Customer cus = db.Customers.Single(c => c.CompanyName == "Maison Dewey");
   7:  cus.Country = "IL";
   8:  db.SubmitChanges();

 

Delete data

   1:  Northwind db = new Northwind();
   2:  var customers = from c in db.Customers
   3:                  where c.CompanyName == "Cactus Comidas para llevar"
   4:                  select c;
   5:   
   6:   
   7:  db.Customers.RemoveAll(customers);
   8:  db.SubmitChanges();

 

Summary

LINQ provides a simple set of standard operators to query in-memory collections as well as entities. LINQ for SQL allows us to create DAL’s quickly but more importantly they are more flexible and robust than the common approach.

This is only the first post about LINQ. I'll continue to expand it. This is only the introduction.

 

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

תגובה אחת

  1. Marina30 באוקטובר 2007 ב 10:00

    Hi Maor
    There is so much useful anf helpful information !
    I believe that another programmers would also enjoy learning through this blog.
    Thank you very much:)
    Marina.
    P.S
    Avodat kodesh ata ose,ein kamoha:)

    הגב