Linq to SQL: Writing clean code

Linq to SQL: Writing clean code

  • Comments 2

As you know with Orcas Beta 1 we have Linq to SQL template available. There we can drag and drop any database table and the code will be ready for you to use. What if you are not a wizard addicted like me and wants to write your own clean code?


I love the conciseness of the C# 3.0 and the lesser code strategy. Let’s try to write some clean code which will allow us to use the relationship also. I will use Northwind and will use Products and Category table. But I am interested in only few selected columns














I will write my own Linq to SQL code and use my own mapping. You always need to use two major namespaces


using System.Data.Linq;

using System.Data.Linq.Mapping;


I will create a mappings between my class property and SQL columns. For that I need to use couple of attributes. Let’s try that out


#region Products Class


public class Products



    public int ProductId{get;set;}



    public string ProductName { get; set; }



    public int CategoryID { get; set; }



    public decimal UnitPrice { get; set; }




#region Categories Class

[Table(Name = "Categories")]

public class Categories


    [Column(IsPrimaryKey = true)]

    public int CategoryID { get; set; }



    public string CategoryName { get; set; }





Now I am ready to go.


Let’s suppose I have one console application, so the code will look like,


static void Main(string[] args)


    DataContext db = new DataContext

(@"Data Source=BLR2B03-A\SQLEXPRESS;Initial Catalog=Northwind;");


    var products = db.GetTable<Products>();

    var categories = db.GetTable<Categories>();


    var q = from p in products

            join c in categories

  on p.CategoryID equals c.CategoryID                   

            select new { p.ProductName, c.CategoryName };






That’s all. Isn’t it much cleaner code? Happy weekend.



Leave a Comment
  • Please add 6 and 7 and type the answer here:
  • Post
  • I have tried it, and it's worked!

    Congratulation! Really a good code , and clean!

    Do You know any Developer Program for SQL coding?

    I'm searching something for myself, because in my new workplace I need to learn the SQL!

    If you can please send Me a link where I can download a developer prog. for using with  MSSQL!


  • SQL Server related webcasts are available



Page 1 of 1 (2 items)