25
Jun
2008

Experimental LINQ to SQL template

Whilst 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 LINQ to SQL template for T4 v0.1 (ZIP) (3 KB)

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

Share with others
  • Digg
  • description
  • StumbleUpon
  • description
  • Reddit
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • Technorati
  • E-mail this story to a friend!

3 Responses to “Experimental LINQ to SQL template”


  1. Gravatar 1 gabriel Jul 19th, 2008 at 17:07

    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.

  2. Gravatar 2 Damien Guard Jul 19th, 2008 at 23:07

    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.

    [)amien

  1. 1 Oleg Sych - » T4 Templates for LINQ to SQL and Entity Framework Pingback on Jun 27th, 2008 at 21:06

Leave a reply




Topics