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 :)
- 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
- Watch a screencast about T4 in action (download, embedded player is awful)
- Grab T4 Editor for IntelliSense within T4 and T4 Template Items for Add New Item... support
- Check out Oleg Sych's blog for great T4 articles including how to enable the 3.5 compiler for templates
- Learn about T4 debugging
[)amien












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.
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