LINQ to SQL T4 template reloaded
A newer version of this LINQ to SQL template is available.
The topic of modifying the code generation phase of LINQ to SQL comes up quite often and the limited T4 template I published here last month was good at showing the potential but wasn’t a practical replacement for the code generation phase.
I am please to make available the next version, which now…
- Runs from the DBML therefore keeping the designer in the loop
- Generate all the attributes for columns and tables including UpdateCheck, IsDbGenerated etc.
- Supports associations including those with a foreign key
- Generates appropriate attributes and code for both serialization modes
In short it generates code that is now functionally equivalent to SQL Metal with the following caveats:
- C# only – VB.NET can be added if there is some interest
- Stored procedures – not yet supported
- Table inheritance – incomplete
- DBML changes require you open and re-save the T4 template so it regenerates the code
- Unidirectional serialization requires you add System.Runtime.Serialization to your project references (thanks Roger!)
To use the template :
- Extract the archive and add the two files to your project
- Right-click on the L2ST4.tt file, choose Properties and set the Custom Tool to blank
- Rename DataClasses1.tt to the same name as your DBML file (but keeping the .tt extension) and open it
- Click save and watch a freshly generate C# DataContext pop out
- Switch off the LINQ to SQL designer generated C# by either setting the Custom Tool on the DBML to blank or setting the Build Action on the generated C# to None.
L2ST4.tt contains a lightweight wrapper around the DBML which is processed using LINQ to XML making the template easier to work with and providing a central for naming rules etc.
This code should be treated as a sample and hasn’t received much testing yet so feel free to leave comments or feedback here.
Some places you could take this template:
- Generate an interface for your data context to improve mocking
- Alternative naming and defaults
- Splitting output into multiple files
- New languages