views:

163

answers:

2

With T4 templates, does it give you the database as an object where you can spit out code?

or do you need that tool visualt4?

+2  A: 

Although there is nothing built into T4 itself specifically for accessing database metadata, you can use any existing .NET APIs. In particular, if you only need to work with SQL Server, you can use SMO (http://msdn.microsoft.com/en-us/library/ms162169.aspx), which is very well designed and easy to use. Here is an example: http://www.olegsych.com/2008/09/t4-tutorial-creatating-your-first-code-generator/.

Oleg

Oleg Sych
are you writing the output to a file though? like mytable.cs?
mrblah
A: 

Think of T4 as an ASPX file with server code. HTML is rendered direcly, and all <% %> code blocks are executed and evaluated at runtime.

Same approach here. All code that resides inside <# #> blocks is executed when T4 templating engine executes a template. Within this block you can do whatever framework is able to do. You can open database connections and read data and generate code out of it if you like (same as if you'd connect to the database and generate HTML from table data in an ASPX file).

So you could do this (after you have a DB reader already open):

...
public enum UserTypeFromDBLookupTable
{
    <# while(reader.Read()) { #>
    /// <summary><#= reader.Get("Description") #></summary>
    <#= reader.Get("Name") #> = <#= reader.Get("UserTypeID") #>,

    <# } #>
}
...

and it would output an enumeration for you based on data in some lookup table(*). You can see this is quite powerful and flexible since you can do whatever you with and like.

comment (*)
Code sample doesn't directly work, because it's simplified to show you how things work. For instance I omitted code that would have to remove the last comma

Robert Koritnik