Linq to SQL: Writing clean code

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

Products

++++++

ProductId

ProductName

CategoryID

UnitPrice

Category

++++++

CategoryID

CategoryName

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

[Table(Name="Products")]

public class Products

{

[Column(IsPrimaryKey=true)]

public int ProductId{get;set;}

[Column]

public string ProductName { get; set; }

[Column]

public int CategoryID { get; set; }

[Column]

public decimal UnitPrice { get; set; }

}

#endregion

#region Categories Class

[Table(Name = "Categories")]

public class Categories

{

[Column(IsPrimaryKey = true)]

public int CategoryID { get; set; }

[Column]

public string CategoryName { get; set; }

}

#endregion

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 };

ObjectDumper.Write(q);

}

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

Namoskar!!!