In my last post I talked about how LINQ to SQL greatly simplifies working with database tables in your code. No longer do you need to sprinkle SQL throughout your code and iterate through results to create business objects. LINQ handles it all for you so you can concentrate on what to do with those objects.
What’s amazing is how well LINQ to SQL’s query generator works. If you have started using LINQ to Objects, you know how great it is to find specific objects in a collection, to sort, and even create secondary objects from data. All of this is amazing, but extension methods make it fairly easy to understand what’s happening behind the scenes. When you work with LINQ to SQL, you include the use of a DataContext object. This is where the magic happens.
A DataContext encompasses details about how the database relates to the business objects. This is where you declare that a Person object is an instance of a row from the Persons database table, and the object properties relate to columns. From there, all CRUD operations can be easily generated.
Simple operations are easy enough, but when you start layering on operations like grouping, Take(), and Skip(), the query generation really shines. The DataContext creates an expression tree based on your query, and then executes it when used. This is called deferred execution and is an important distinction. Merely assigning a query to a variable, like this:
var people = from p in DC.People where FirstName == “John” select p;
does not result in any SQL queries being sent. It’s not until you work with the collection that data is retrieved. This makes it possible to reuse a query throughout your code and always have fresh data. If you want to cache your results, simply call ToList() on the query, and it will execute right there. Basically, as long as it’s an enumerable it will execute on each enumeration. Once converted to a list, the results are static.
There are many great resources out there to learn more about LINQ to SQL. Fire up AdventureWorks, Northwind, or your favorite sample data and start trying it out!
Posted Saturday, January 30th, 2010 at 1:09 pm by Arian Kulp
295 views