Experimental LINQ to SQL template

A newer version of this LINQ to SQL template is available.

While SQLMetal does a good job of turning your SQL schema into a set of classes for you it doesn’t let you customize the code generation process.

Usefully there is now a templating system built into Visual Studio 2008 called Text Templates (T4 for short).

Here is a short (369 line) experimental proof-of-concept T4 template I wrote last night that will generate a data context and associated entity classes as a starting point similar to that produced by SQLMetal.

Download of this old version no longer available, see the newer article!

Once downloaded unzip and drop the DataContext.cs.tt into your project and edit line 17 to set the connection string. You can also edit lines 18 and 19 to set the namespace and class name. The lightweight wrappers around database, table and column can be found at the end of the file – they simply wrap the SQL Server Information_Schema views as briefly as possible.

Within seconds Visual Studio should have created a code-behind file for the DataContext named DataContext.cs.cs with your generated code ready to use :) If you don’t like the way the template generates your context you can change it :)

There are limitations with this experimental proof-of-concept including: 

  • Processes all and only tables in the database (no views or SP’s)
  • Foreign-key relationships are not implemented
  • Column attributes for IsDbGenerated, UpdateCheck and AutoSync not implemented
  • C# only (sorry Julie)
  • Plural and singular naming rules are incomplete
  • Can’t modify schema as you could with a designer stage
To learn more about T4: 

[)amien

3 responses

  1. Avatar for gabriel

    Hi, What you have done is fantastic.I am getting to grip with the T4 concept and how to write those templates.

    Is it possible to have a form and button and call the template from a windows form? Any examples anywhere?

    thanks again for sharing this.

    gabriel 19 July 2008
  2. Avatar for Damien Guard

    You can't call the T4 template from your own application as T4 is part of the Visual Studio IDE.

    You can however use the CodeDOM API, CSharpCodeProvider classes and Assembly.Load built into the .NET Framework to develop you own code-building, compilation and execution mechanism from your own applications.

    Damien Guard 19 July 2008
  3. Avatar for Victor Garcia Aprea

    @ Damien:

    1. very nice template!

    2. "...You can't call the T4 template from your own application as T4 is part of the Visual Studio IDE..." --> actually you CAN use the T4 engine from your own apps, note the T4 engine is not tied to VS at all.

    -vga.

    Victor Garcia Aprea 5 October 2008