Over the last few weeks I've been writing a series of blog posts that cover LINQ to SQL.LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .
I'll also show how we can cleanly integrate business rules and custom validation logic with our data model.
In Part 2 of this series I walked through how to create a LINQ to SQL class model using the LINQ to SQL designer that is built-into VS 2008.
Below is a class model created for the Northwind sample database and which I'll be using in this blog post: When we designed our data model using the LINQ to SQL data designer above we defined five data model classes: Product, Category, Customer, Order and Order Detail.
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.
When we defined our data model, the LINQ to SQL designer also created a custom Data Context class that provides the main conduit by which we'll query our database and apply updates/changes.In the example data model we defined above this class was named "Northwind Data Context".The Northwind Data Context class has properties that represent each Table we modeled within the database (specifically: Products, Categories, Customers, Orders, Order Details).As I covered in Part 3 of this blog series, we can easily use LINQ syntax expressions to query and retrieve data from our database using this Northwind Data Context class.LINQ to SQL will then automatically translate these LINQ query expressions to the appropriate SQL code to execute at runtime.For example, I could write the below LINQ expression to retrieve a single Product object by searching on the Product name: I could then write the LINQ query expression below to retrieve all products from the database that haven't yet had an order placed for them, and which also cost more than 0: Note above how I am using the "Order Details" association for each product as part of the query to only retrieve those products that have not had any orders placed for them.