TAG: O/R Mappers
I have been presenting on LINQ To SQL quite a bit over the past couple of months. I completed a talk called SQL Server Data Access Tips & Techniques at Tampa SQL Saturday as well as have given a presentation called LINQ To SQL Tips & Techniques at the South Florida Code Camp 2009 and at Ft. Myers Florida User Group.
LINQ To SQL and ADO.NET
One of the topics that seems to be new to developers is using LINQ To SQL for ADO.NET in addition to as an O/R Mapper. In a previous post I mentioned using LINQ To SQL for ADO.NET Commands:
and in this tutorial I want to show how one can use LINQ To SQL for executing ADO.NET Queries.
As an example, let's say we want to do something as simple as execute a query in ADO.NET to select a RegionDescription in the Region Table in Northwind where RegionID = 1. Writing this query using LINQ To SQL is as simple as:
using (var dc = new NorthwindDataContext())
{
var region =
dc.ExecuteQuery<string>("SELECT RegionDescription
FROM Region WHERE RegionID = {0}", 1).Single();
}
This is identical to the following ADO.NET code using System.Data.SqlClient:
using (
var connection = new SqlConnection("..."))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText =
"SELECT RegionDescription FROM Region WHERE RegionID = @RegionID";
command.Parameters.AddWithValue("@RegionID", 1);
connection.Open();
var region = (string) command.ExecuteScalar();
}
}
You decide which code you like, but as the code sample shows one can use LINQ To SQL for ADO.NET without using it as an O/R Mapper and the LINQ To SQL ADO.NET is pretty simple. One doesn't have to worry about connection management and creating commands and parameters with LINQ To SQL.
Conclusion
LINQ To SQL is more than just an O/R Mapper and helps simplify the ADO.NET code as well as adhere to ADO.NET best practices.