TAG: LINQ To SQL Tutorials, O/R Mappers
To those of you who have used LINQ To SQL quite a bit this is probably stating the obvious, but LINQ To SQL can be used for ADO.NET as well as O/R Mapping. There seems to be this misconception by many developers that LINQ To SQL is only an O/R Mapper, but in truth, you can use it in your application where you need ADO.NET functionality like executing queries and commands.
As an example, let's say we want to do something as simple as execute a command in ADO.NET to insert a new Region in the Region Table in Northwind. There are two fields, RegionID and RegionDescription, and for some unknown reason RegionID is not an identity field in my copy ( which I may have altered to test something in the past ), so I need to supply both values in the INSERT statement. Using LINQ To SQL to execute this ADO.NET INSERT command is as simple as follows:
using (NorthwindDataContext dc = new NorthwindDataContext())
{
int rowsAffected = dc.ExecuteCommand("INSERT INTO Region VALUES ({0},{1})",5, "Test Region");
}
Compare that little amount of code to using System.Data.SqlClient:
using (var connection = new SqlConnection("..."))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Region VALUES (@RegionID,@RegionDescription)";
command.Parameters.AddWithValue("@RegionID", 5);
command.Parameters.AddWithValue("@RegionDescription", "Test Region");
connection.Open();
int rowsAffected = command.ExecuteNonQuery();
}
}
Using LINQ To SQL is much simpler by far.
LINQ To SQL Tutorials