Quantcast
Channel: Shahnawaz's Blog » ASP.NET
Viewing all articles
Browse latest Browse all 3

Understanding LINQ Basics

$
0
0

I’ll introduced you the LINQ which is a part of Microsoft’s .Net Framework. We will learn some basic building blocks like What is LINQ, what’s its uses, how to use it.

What is LINQ?

Well LINQ means Language-INtegrated Query, a set of language extensions that allows you to perform queries without leaving the comfort of the programming language like C# and VB.NET

The original motivation behind LINQ was to address the conceptual and technical difficulties encountered when using databases with .NET programming languages. With LINQ, Microsoft’s intention was to provide a solution for the problem of object-relational mapping, as well as to simplify the interaction between objects and data sources. LINQ eventually evolved into a general-purpose language-integrated querying toolset. This toolset can be used to access data coming from in-memory objects (LINQ to Objects), databases (LINQ to SQL), XML documents (LINQ to XML), a file-system, or any other source.

LINQ unifies data access, whatever the source of data, and allows mixing data from different kind of sources. It allows for query and set operations, similar to what SQL statements offer for databases.

LINQ integrates SQL like queries directly within .NET languages such as C# and Visual Basic.

If you are curious about What is LINQ then you can learn more here.

LINQ Basics

The easiest way to approach LINQ is to consider how it works with in-memory collections. This is LINQ to Objects—the simplest form of LINQ.

Essentially, LINQ to Objects allows you to replace iteration logic (such as a foreach block) with a declarative LINQ expression.

For example, imagine you want to show a list of all item contained in a array of type string, then you would write C# code as:

string[] words = new string[] {
"Shahnawaz", "Khan", "post", "blog", "on", "LINQ" };

foreach (string word in words)
{
    Console.WriteLine(word);
}

Same example written in LINQ as:

   1: string[] words =
   2: { "Shahnawaz", "Khan", "post", "blog", "on", "LINQ" };
   3:  
   4: var myWords = from word in words
   5:                  select word;
   6:  
   7: foreach (var word in myWords)
   8:     label1.Text += word + " ";

However, normal c# code is much shorter than the LINQ version, but LINQ provides greater flexibility.

Example of calculating total sum, like:

   1: //Code
   2: int[] nums = new int[] {1,0,2,5,4,8,3};
   3:  
   4: int result = nums.Sum();
   5: Console.WriteLine(result);
   6: //Output: 23

LINQ to XML

LINQ to XML is a innovative way to work with XML data in the .NET languages. This new API simplifies working with XML data. One aspect of LINQ to XML is that it supports writing Query Expressions to create or use XML data as a source or destination format.

Suppose you need to create simple xml document like:

  1: <employees>
  2:   <employee eId="1234">
  3:     <firstName>Shahnawaz</firstName>
  4:     <lastName>Khan</lastName>
  5:   </employee>
  6:   <employee eId="6798">
  7:     <firstName>John</firstName>
  8:     <lastName>Cena</lastName>
  9:   </employee>
 10: </employees>

You would write LINQ Code in c# like:

  1: XElement xml = new XElement("employees",
  2:                     new XElement("employee", 
  3:                         new XAttribute("eId", "1234"),
  4:                         new XElement("firstName", "Shahnawaz"),
  5:                         new XElement("lastName", "Khan")
  6:                     ),
  7:                     new XElement("employee", 
  8:                         new XAttribute("eId", "6798"),
  9:                         new XElement("firstName", "John"),
 10:                         new XElement("lastName", "Cena")
 11:                     )
 12:                 ); 
 13:  
 14: Console.WriteLine(xml);

In the above example we create xml structure by hand, it’s good when the structure is small as two child nodes, what if we have to build large xml document coming from a data store? We can create xml from data source like this:

  1: // Build xml fragment based on collection
  2: XElement xml = new XElement("employees",
  3:                     from e in db.Employees
  4:                     select new XElement("employee",
  5:                               new XAttribute("eId", e.EmpId),
  6:                               new XElement("firstName", e.FirstName),
  7:                               new XElement("lastName", e.LastName))
  8:                     );
  9: 
 10: Console.WriteLine(xml); // Dump XML to console

LINQ to SQL

LINQ to SQL provides language-integrated data access by using LINQ’s extension mechanism. It builds on ADO.NET to map tables and rows to classes and objects.

The simplest query using LINQ to SQL may be like this:

  1: from contact in db.GetTable<Contact>()
  2: where contact.City == "Paris"
  3: select contact;

This query works on a list of contacts from a database. Notice the difference between the two queries. Only the object on which we are working is different; the query syntax is exactly the same. This shows how we’ll be able to work the same way with multiple types of data. The LINQ is Flexible!

You’re probably wondering what db.GetTable<Contact>() means in above LINQ to SQL query.

Entity Class

The first step in building a LINQ to SQL application is declaring the classes, which is called Entity Class.

In the example below, we’ll define a class named Contact and associate it with the Contacts table of the Northwind sample database with the LINQ code. for this to work, we need only to apply a custom attribute to the class:

The Table attribute is provided by LINQ to SQL in the System.Data.Linq.Mapping namespace. It has a Name property that is used to specify the name of the database table.

In addition to associating entity classes with tables, we need to denote each field or property we intend to associate with a column of the table. This is done with the Column attribute:

   1: [Table(Name="Contacts")]
   2: class Contact
   3:     {
   4:         [Column(IsPrimaryKey=true)]
   5:         public int ContactID { get; set; }
   6:         [Column(Name="ContactName"]
   7:         public string Name { get; set; }
   8:         [Column]
   9:         public string City { get; set; }
  10:     }

The Column attribute is also part of the System.Data.Linq.Mapping namespace. It has a variety of properties we can use to customize the exact mapping between

our fields or properties and the database’s columns. You can see that we use the IsPrimaryKey property to tell LINQ to SQL that the table column named ContactID is part of the table’s primary key. Notice how we indicate that the ContactName column is to be mapped to the Name field. We don’t specify the names of

the other columns or the types of the columns: In our case, LINQ to SQL will deduce them from the fields of the class.

The DataContext

The next thing we need is a System.Data.Linq.DataContext object. The purpose of DataContext is to translate requests for objects into SQL queries made against the database and

then assemble objects out of the results.

We will use the Northwnd.mdf database. I assume that this database is in the Data directory, then we create DataContext object like this:

  1: string path = Path.GetFullPath(@"..\..\Data\northwnd.mdf");
  2: DataContext db = new DataContext(path);

The DataContext provides access to the tables in the database. Here is how to get access to the Contacts table mapped to our Contact class:

  1: Table<Contact> contacts = db.GetTable<Contact>();

DataContext.GetTable is a generic method, which allows us to work with strongly typed objects. This is what will allow us to use a LINQ query.

A complete code sample for above example is as follows:

   1: using System;
   2: using System.Linq;
   3: using System.Data.Linq;
   4: using System.Data.Linq.Mapping;
   5:  
   6: static class HelloLinqToSql
   7: {
   8:     [Table(Name="Contacts")]
   9:     class Contact
  10:     {
  11:         [Column(IsPrimaryKey=true)]
  12:         public int ContactID { get; set; }
  13:         [Column(Name="ContactName")]
  14:         public string Name { get; set; }
  15:         [Column]
  16:         public string City { get; set; }
  17:     }
  18:     static void Main()
  19:     {
  20:         //Get Access to database
  21:         string path = System.IO.Path.GetFullPath(@"..\..\Data\northwnd.mdf");
  22:         DataContext db = new DataContext(path);
  23:         //Query for contacts with where clause
  24:         var contacts = from contact in db.GetTable<Contact>()
  25:                         where contact.City == "London"
  26:                         select contact;
  27:         //Display list of matching contacts
  28:         foreach (var contact in contacts)
  29:         Console.WriteLine("Hello "+contact.Name);
  30:     }
  31: }

This is a simple example, but it gives you a good idea of what LINQ to SQL has to offer and how it could change the way you work with databases.

You can think after seeing this example, that we didn’t specify the data source and open connection to database. This is because of SQL Server 2005 Express edition and above we can only supply path to the database itself and it’ll do automatically for us, let’s see what’s it did for us automatically.

  • Opening a connection to the database
  • Generating the SQL query
  • Executing the SQL query against the database
  • Creating and filling our objects

You have seen that LINQ to SQL is able to generate dynamic SQL queries based on language-integrated queries. This may not be adapted to every situation, and so LINQ to SQL also supports custom SQL queries and stored procedures so that we can use our own handwritten SQL code and still benefit from the LINQ to

SQL infrastructure.

To get a better understanding of how LINQ to SQL works, we created our entity classes and provided the mapping information. In practice, typically this code would be generated by tools that come with LINQ to SQL or using the graphical LINQ to SQL Designer.

LINQ to SQL is a feature rich and includes things such as support for data binding, interoperability with ADO.NET, concurrency management, support for inheritance, and help for debugging.

I’m not cover everything here as it’s LINQ basic, in the near future I’ll write more on LINQ.

Thanks for reading my blog post

Hope this works!



Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images