Wednesday, 29 February 2012

LINQ to SQL


LINQ to SQL makes database programming a direct part of the VB.NET/C#  language. Before it was added to the language toolkit with Framework 3.5/VB.NET 2008, databases were a world apart from your application programming code and you had to get your data through an interface. Coding for SQL Server this way doesn't take advantage of some of the best features of VB.NET/C# development such as the use of  Intellisense. (Using older methods, the tables and fields in the database are unknown to the VB.NET code so Visual Studio can't tell you whether your names are right or wrong. And the compiler can't tell you whether your SQL commands are correct because they're passed directly to SQL Server. Your code has to be able to interpret whatever comes back from SQL Server.)

There are basically two problems to be solved when accessing a SQL Server database from your application:
  1. Data in a database doesn't have the same "types" as data in .NET. This is often called the database "impedance mismatch".  The process of converting types from a database into types in an application is called object relational mapping (ORM).  Today, LINQ to SQL provides a new tool in Visual Studio, the Object Relational Designer, and just takes care of the rest of the problem.
  2. SQL statements have to be passed to the database engine for execution and results (or errors) returned to the application. The SqlClient namespace in ADO.NET provides the ExecuteReader, ExecuteNonQuery, and ExecuteScalar methods to run queries. Part of the problem is that it's not always clear which one to use. LINQ to SQL gives you VB.NET/C# statements that you can compile in your application and eliminates the need to use these methods. The new LINQ to SQL syntax looks a lot like traditional SQL too.
Create SQL to SQL:
  1. Add database connection
  2. Add DataContext (LINQ to SQL Classes) (".dbml")

The bottom line is that LINQ to SQL is a lightweight technology that can make your SQL Server coding faster and easier. It's a good choice for most projects, but if you need the best performance or if your application has complex requirements, you might want to go the traditional route or consider the ADO.NET Entity Framework.

Relational Data Model            LINQ to SQL Object Model 
----------------------------     -------------------------------
Table                            Entity class
Column                           Class member 
Foreign-key relationship         Association 
Stored Procedure or Function     Method


No comments:

Post a Comment