Sunday, May 15, 2011


LINQ to SQL allows .NET developers to write “queries” in their .NET language of choice to retrieve and manipulate data from a SQL Server database. In a general sense, LINQ to SQL allows us to create SQL queries in our preferred .NET language syntax and work with a strongly types collection of objects as a return result. We can make changes to these objects then save changes back to the database.

To get an idea of the syntax for LINQ to SQL, we will be using the following SQL database schema. It is a simple software registration and helpdesk. It is populated with sample data and has foreign-key relationships defined where appropriate.

SQL Database Schema used for LINQ to SQL examples
SQL Database Schema used for LINQ to SQL examples.

For the moment I ask you to ignore the fact that we will be coding against a type HookedOnLINQ, I’ll get to how that was created in a few pages time, for now just understand it is an object structure that mimics this database schema.

HookedOnLINQ db = new HookedOnLINQ("Data Source=(local);Initial Catalog=HookedOnLINQ");   var q = from c in db.Contact where c.DateOfBirth.AddYears(35) > DateTime.Now orderby c.DateOfBirth descending select c;   foreach(var c in q) Console.WriteLine("{0} {1} b.{2}", c.FirstName.Trim(), c.LastName.Trim(),c.DateOfBirth.ToString("dd-MMM-yyyy"));   Output: Mack Kamph b.17-Sep-1977 Armando Valdes b.09-Dec-1973

See full details:

No comments: