Sunday, December 6, 2009

Compiler Awareness of DB Schema Change

After Hibernate buzzing for so long, Microsoft brought LINQ as it's first ORM solution.

In the essence, ORM brings to an application a domain layer with integrated data access functionality.

Even LINQ to SQL maybe not as powerful as Hibernate(people complaint it can not map inheritance - it is simple one table to one object mapping - Entity Framework will come with full power), but I think it has already demonstrated us the power of ORM - we don't need to do the very tidious database call and transformation from relational data to object oriented data.

One feature LINQ to SQL over older ADO.Net is the compiler awareness of DB schema change. This says that code mismatches caused by changes in database end will be detected and fixed rather than in runtime.

Unawareness with ADO.Net:

string name = reader["Name"].ToString(); //or
string name = reader[1].ToString();


Because the column in database is refered as a string "Name" or index number, It won't cause any compile error if the column name or order is changed in database.

With LINQ to SQL, when DB schema is changed, we use SQLMetal tool to regenerate LINQ classes, the properties and methods are generated accordingly. So any mismatch of code that uses LINQ classes will be caught by the compiler.

SQLMetal generated classes reflect the following type of schema objects:
stored procedure
function
table
view

An example of a LINQ based DAL
..


Defered execution

Let us first define a query:

IQueryable<Category> myQueryable =
from cat in categories
select cat;
Category cat = myQueryable.where(c=>c.id==1).SingleOrDefault;

The query won't really execute until we really access the IQuerable myQueryable. e.g.
myQueryable.ToList(); // or
myQueryable.Count(); // or
cat.Name;

No comments: