Wednesday, September 17, 2008

LINQ to SQL in Practice

By S.Luann

Two tools you can use to generate domain types from data model in a database:
- SQLMetal.exe - commandline tool
- Object Relational Designer - comes with VS 2008

with Object Relational Designer you can customize a great deal because it has GUI and you can drag and drop with it.
for example, you can change the default, auto-generated SQL statements for CRUD with stored procedures.


There are three operation involved in the process of generating OO types from given database schema.

1. DBML Extractor generate dbml file (xml format) from db schema,
2. XSD validator scan and check the dbml file against dbml schema[1]
3. Code Generator generate classes

there are two types of types to be mapped:
attribute-based and external xml

As a result, there are two different dbml file for mapping each of the types. Also we a xsd standards to verify external dbml file[2].

A attribute-based mapped domain type is something like:

[CustomerTable]
class Customer
{
[CustomerIDColumn]
public string CustomerID
{
get;
set;
}
}

external mapped types is said has the benefit that some changes can be accomplished by changing the external xml file, in other words, the external xml file is like a confuration file, in cerain scenario you can update by only change the xml file while not change domain types.

there is a controversy out there on whether to user stored procedures. LINQ to SQL is not expected to use stored procedure. it automatically generated CRUD statements. In this case all business logic should be moved to business logic layer. however a lot of people like to write business logic in stored procedure. they believe stored procedure is easier to maitain, because not need to compile the whole application.
but others say there is nother better than LINQ, Linq is optimized and can do any data manipulation operation to meed broad data needs, with stored procedure, you end up have a huge number of them to meed the same needs.

the following namespaces have the APIs for LINQ to SQL
using System.Data.Linq;
using System.Data.Linq.Mapping;

Reference
[1] dbml XML Schema File,
http://msdn.microsoft.com/en-us/library/bb399400.aspx
[2] External Mapping Reference (LINQ to SQL),
http://msdn.microsoft.com/en-us/library/bb386907.aspx

No comments: