Robust, Efficient, & Fast Data Access With LINQ to SQL
In the post I have quickly captured the steps required to access a database using LINQ to SQL. I am reading a book LINQ in Action – good read, easy and practical. Love it a lot. | Quick Resource Box |
General ORM LimitationsIn the book the authors specify key limitations of existing ORM [object relational mapping] tools:
I’d summarize the summary as “ORM usually hit developer’s and/or code’s performance. ” Accessing Database with LINQ to SQLSummary of steps:
The following section describes each step in details. Step 1 – Create entity class I am using Pet Shop database. I have created a simple ProductInfo entity [Table] class as follows: [Table(Name = "Product")] public class ProductInfo { [Column (IsPrimaryKey=true, Name="ProductId")] public string ID { get; set; } [Column] public string Name { get; set; } [Column (Name="Descn")] public string Description { get; set; } [Column (Name="CategoryId")] public string Category { get; set; } } Notice the annotations for each property. The annotations actually map the class’ properties to the table’s fields. Step 2 – Write LINQ to SQL Query Next is creating the DataContext object – effectively the connection to the database, and then building the query: DataContext db = new DataContext(\@"Data Source=.\sqlexpress; Initial Catalog=MSPetShop4; Integrated Security=True"); var products= from product in db.GetTable<ProductInfo>() where product.Category.Equals("FISH") select product; Step 3 – Test your code To test the code I have dumped the values to the console and received the result: foreach (ProductInfo product in products) { Console.WriteLine("NAME {0} DESCRIPTION {1}", product.Name, product.Description); }
I have also ran a SQL Express Profiler to observe the SQL Statement issued against the DB":
AnalysisIn the book authors summarize the efficiency of the approach as follows:
As performance guy I must also add the LINQ to SQL closes/disposes the connection automatically. In too many cases developers neglect closing/disposing the connection which usually leads to connection leak and as a result to unstable or less than optimal performance. ConclusionSeems like LINQ to SQL breaks the limitations I have mentioned in the beginning. For my Solution Architecture For the Masses series I am using old school database approach. I believe since the solution I have build utilizes layered approach and since the layers are abstracted one from another I will be porting the DAL [Data Access Layer] from ADO.NET to LINQ to SQL. Read the book LINQ in Action. Related Books |
Comments
- Anonymous
May 25, 2010
Hasn't Microsoft stopped work on LINQ to SQL? Shouldn't you be using the Entity Framework and LINQ to Entities? - Anonymous
May 25, 2010
The comment has been removed