<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nathan Bridgewater &#187; T4</title>
	<atom:link href="http://www.integratedwebsystems.com/tag/t4/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.integratedwebsystems.com</link>
	<description>My Little .NET Sandbox</description>
	<lastBuildDate>Thu, 19 Jan 2012 20:37:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Setting up SubSonic3 Repository Mode with an Existing Database</title>
		<link>http://www.integratedwebsystems.com/2010/10/setting-up-subsonic3-repository-mode-with-an-existing-database/</link>
		<comments>http://www.integratedwebsystems.com/2010/10/setting-up-subsonic3-repository-mode-with-an-existing-database/#comments</comments>
		<pubDate>Wed, 06 Oct 2010 17:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[SubSonic]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Repository]]></category>
		<category><![CDATA[T4]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=973</guid>
		<description><![CDATA[Using SubSonic 3 respository mode has been a breath of fresh air...]]></description>
			<content:encoded><![CDATA[<p>Using <a href="http://www.subsonicproject.com/">SubSonic 3</a> <a href="http://subsonicproject.com/docs/Using_SimpleRepository">respository mode</a> has been a breath of fresh air for some of my projects. You can use simple POCOs (plain old CLR objects) and easily use <a href="http://msdn.microsoft.com/en-us/library/aa973811.aspx">inversion of control</a> with your application. However, it can be a little confusing using repository mode with an existing database since SubSonic’s default schema naming may not conform to your database. By using SubSonic’s schema attributes, you can get your application up and running relatively easily; and if you have a ton of tables, I have a T4 template that generates basic domain classes against your database to get you started. </p>
<p> <span id="more-973"></span><br />
<h3>Conforming to Your Database</h3>
<p>So first off: naming. SubSonic3 repository assumes that all your tables are pascal-cased and pluralized. So if you use a vanilla domain class against your database, it will only work with tables matching that naming pattern. Be aware that these attributes help determine the <em>database </em>properties; not the .NET runtime behavior of your application.&#160; For example, a <em>StringLength </em>attribute will instruct SubSonic to setup a varchar column with a defined length, but your .NET runtime will still use a String type and will still accept values longer than the associated database column.&#160; Here are the attributes you can use to tailor your classes to your database. </p>
<p><em>SubSonic.SqlGeneration.Schema </em>including<em>:</em></p>
<ul>
<li>[SubSonicDefaultSetting] – set a default value </li>
<li>[SubSonicIgnore] – Ignore a property or field </li>
<li>[SubSonicLongString] – ntext or text field </li>
<li>[SubSonicNullString] – Nullable varchar or text </li>
<li>[SubSonicNumericPrecision] – decimal with specific precision </li>
<li>[SubSonicPrimaryKey] – override primary key (use for primary key properties not named “Id”) </li>
<li>[SubSonicStringLength] – varchar custom length (use when length is not 50) </li>
<li>[SubSonicTableNameOverride] – override table name mapping for class </li>
<li>[SubSonicToManyRelation] – for one to many foreign key property mappings </li>
<li>[SubSonicToOneRelation] – for one to one foreign key property mappings </li>
</ul>
<p>&#160;</p>
<p>For the most part, you will use the TableNameOverride attribute to make your classes work with their corresponding tables. However, at times you will need to use the PrimaryKey if you don’t use “ID” as your primary key. The rest are extremely handy as well especially when it comes to null strings, text fields, and properties you want to ignore completely from the SQL translation to your database. Here is a sample class from an existing application: </p>
<pre class="brush: csharp; gutter: false;">[SubSonicTableNameOverride(&quot;effect&quot;)]
public partial class Effect
{
    public int Id { get; set; }
    public int SiteId { get; set; }
    public int? EffectTypeId { get; set; }
    public bool ApplyDefault { get; set; }
    [SubSonicNullString]
    [SubSonicStringLength(100)]
    public string Name { get; set; }
    [SubSonicNullString]
    [SubSonicStringLength(500)]
    public string Description { get; set; }
}</pre>
<p>Here, I use Id for my primary key, so it is not necessary to add the <em>PrimaryKey </em>attribute.&#160; I did use a NullString operator for a couple fields here that don’t require values. On a side-note, one of the philosophies behind requiring the NullString attribute and not simply assuming all strings are nullable is that the authors believe it’s more useful to use empty strings in place of null values because it alleviates many other issues down the road.&#160; While I don’t disagree, I still tend to use nullable strings out of habit. You can read more about their conventions from the <a href="http://www.subsonicproject.com/docs/Conventions">SubSonic Tome</a></p>
<h3>Domain Class Generator</h3>
<p>To get up and running quick, I built a simple domain class generator with T4 that writes out basic structures from an existing database repository-mode-friendly format. To run it, copy the files: Settings.ttinclude, SqlServer.ttinclude (or db specific ttinclude), and this Entities_Intial.tt file into your project folder. (Don’t add them to your visual studio project just yet).&#160; Edit the Settings.ttinclude file and customize your namespace, connection string, and database name fields.&#160; </p>
<p>Then include the <em>Entities_Initial.tt</em> file to your project. When you include this file, it will automatically attempt to run with your settings. It should separate each class into its own file. It will also generate a file for the core Entities_Initial that you can safely delete.&#160; (NOTE: To re-run the generation after including it to your project, right-click the <em>Entities_Initial.tt</em> file and select “Run Custom Tool”).</p>
<p>Copy these files to another folder in your project to prevent them from being accidentally overwritten with another generation. Unlike the generated partial classes of ActiveRecord and LinqTemplates where you maintain a partial extension, you want to maintain these domain classes directly because they truly should stand alone from the framework you’re using.&#160; Managing them like this gives you direct control over the properties and attributes in your domain model.&#160; You should also be able to use these classes with other IOC frameworks like NHibernate. (Granted… To drop the SubSonic reference, you will need to drop all the attributes at the same time). </p>
<p>&#160;</p>
<p><strong>Entities_Intial.tt</strong></p>
<pre class="brush: csharp; gutter: false;">&lt;#@ template language=&quot;C#v3.5&quot; debug=&quot;True&quot; hostspecific=&quot;True&quot; #&gt;
&lt;#@ include file=&quot;SQLServer.ttinclude&quot; #&gt;
&lt;#
    var list = LoadTables();
    foreach (Table table in list)
    {
#&gt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Collections;
using System.ComponentModel;
using System.Data.Common;
using SubSonic.SqlGeneration.Schema;

namespace &lt;#=Namespace #&gt;
{
    [SubSonicTableNameOverride(&quot;&lt;#=table.Name#&gt;&quot;)]
    public partial class &lt;#=table.CleanName#&gt;
    {
&lt;#
        foreach(Column col in table.Columns)
        {
            if (col.IsPK &amp;&amp; col.CleanName.ToLower() != &quot;id&quot;)
            {
#&gt;        [SubSonicPrimaryKey]
&lt;#            }

            var nullableNonString = string.Empty;
            var nullableString = string.Empty;
            if (col.IsNullable &amp;&amp; col.SysType != &quot;string&quot;)
            {
                nullableNonString = &quot;?&quot;;
            }
            if (col.SysType == &quot;string&quot;){
                if (col.IsNullable)
                {
#&gt;        [SubSonicNullString]
&lt;#                }
                if (col.DataType == &quot;text&quot;)
                {
#&gt;        [SubSonicLongString]
&lt;#                }
                else
                {
#&gt;        [SubSonicStringLength(&lt;#=col.MaxLength#&gt;)]
&lt;#                }
            }
#&gt;        public &lt;#=col.SysType#&gt;&lt;#=nullableNonString#&gt; &lt;#=col.CleanName#&gt; { get; set; }
&lt;#
        }
#&gt;
    }
}
&lt;#    SaveOutput(table.CleanName + &quot;.cs&quot;);
    }
#&gt;
}</pre>
<p>You can download the original script and its references <a href="/resources/p973/SubSonic-T4-Helpers.zip">directly</a> or get the <a href="http://github.com/nathanb/iws-snippets/tree/master/SubSonic-T4-Helpers">latest version</a> from my <a href="http://github.com/nathanb/iws-snippets">snippets project on GitHub</a>. I used the base elements of the T4 scripts from the <a href="http://github.com/subsonic/SubSonic-3.0-Templates">SubSonic-Templates project</a> for this. Currently, they only support MySql, Sql Server, and Sqlite databases. </p>
<p>Enjoy! </p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/10/setting-up-subsonic3-repository-mode-with-an-existing-database/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SubSonic3 Works on Mono!</title>
		<link>http://www.integratedwebsystems.com/2010/08/subsonic3-works-on-mono/</link>
		<comments>http://www.integratedwebsystems.com/2010/08/subsonic3-works-on-mono/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 05:00:00 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[ADO.Net]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[Mono]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[SubSonic]]></category>
		<category><![CDATA[T4]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=773</guid>
		<description><![CDATA[So a couple weeks ago I decided to test a few changes...]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.subsonicproject.com"><img style="border-right-width: 0px; width: 280px; margin-bottom: 1em; float: right; border-top-width: 0px; border-bottom-width: 0px; height: 41px; margin-left: 1em; border-left-width: 0px" alt="SubSonic  Project" src="http://www.subsonicproject.com/content/images/SubSonicSMall.png" /></a>So a couple weeks ago I decided to test a few changes made to <a href="http://www.subsonicproject.com">SubSonic3</a> that fixed a LINQ evaluation bug related to medium trust. Using a simple console app on linux/mono, I tested basic data access to a SQLite database using repository mode, and to my surprise it worked! </p>
<p><a href="http://www.mono-project.com"><img style="border-right-width: 0px; margin: 0px 10px 10px 0px; width: 100px; display: inline; float: left; border-top-width: 0px; border-bottom-width: 0px; height: 120px; border-left-width: 0px" title="Mono-gorilla-aqua.100px" border="0" alt="Mono-gorilla-aqua.100px" src="http://www.integratedwebsystems.com/wp-content/uploads/2010/08/Monogorillaaqua.100px1.png" width="100" height="120" /></a></p>
<p>I&#8217;ve always been a big fan of SubSonic since its 2.0 version, which I used for a mid-sized e-commerce site. With a totally rewritten core, 3.0 uses LINQ (language integrated query) for all of its data access providing a great alternative to Dblinq for the Mono platform.</p>
<p>&#160;</p>
<p>&#160;</p>
</p>
<p> <span id="more-773"></span>
</p>
<p>SubSonic3 supports <a href="http://www.subsonicproject.com/docs/Using_ActiveRecord">ActiveRecord</a>, <a href="http://subsonicproject.com/docs/Using_SimpleRepository">Repository</a>, and <a href="http://www.subsonicproject.com/docs/Using_AdvancedTemplates">Custom Linq</a> modes, which give you the flexibility to build code-first or database-first.&#160; SubSonic3 is not an ORM (object relational mapping) like <a href="http://www.nhibernate.com/">NHibernate</a>, but it can behave like one when you use Repository Mode using POCO (plain old CLR object) representations of your tables. SubSonic handles the mapping and database query generation itself based on the database provider configured. Its intention is to allow you to build code-first and let the persistence of the object be non-critical to your application. It can even migrate your class definition changes (table schema) to the database automatically during runtime; however, it still has the flexibility to let you design your database with keys, indexes, and constraints yourself without using the automatic migration. The <a href="http://www.subsonicproject.com">SubSonic website</a> has a <a href="http://subsonicproject.com/docs/Simple_Repo_5_Minute_Demo">great demo</a> showing this capability.</p>
<h3>Database Independence</h3>
<p>To make SubSonc3 truly database agnostic, you have to use Repository mode. Active Record and Custom Linq modes DO support multiple database engines, but they all require custom class generation which is hard-wired to those engines. So when you change database types like from MySql to MSSQL or vice-versa, you have to regenerate your classes.</p>
<p>With Repository mode, you simply change your connection string in the app.config. It will use the 2.0 Data Provider model provided by the database engine client and the definition of your POCO classes to determine the SQL syntax and schema to use.&#160; SubSonic is pre-wired with MSSql, SQLite, MySql, and a generic ANSI Sql syntax support. There&#8217;s been lots of talk about implementing Oracle and PostgreSql, which may already work in ActiveRecord or LinqTemplates, but are not yet in the Core assembly for use with Repository.</p>
<h3>Decoupled &#8211; Mocking for Unit Tests and Framework Independence</h3>
<p>Another big advantage of Repository is the ability to decouple your data framework from your application completely. Since the POCO objects are not directly tied to SubSonic, they can be re-used with other frameworks like <a href="http://www.nhibernate.com">NHibernate</a> or the latest <a href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx">Entity Framework 4</a> without touching a single line of application code. It also opens the door to mocking and testability. Dependency Injection frameworks like <a href="http://unity.codeplex.com/">Unity</a> or <a href="http://structuremap.github.com/structuremap/index.html">StructureMap</a> work perfect for this.</p>
<h3>So how about a sample?</h3>
<p>This is a silly little test application that is neither pretty nor elegant, but it proves that this code will run on Mono 2.6.3 and 2.7 (trunk) with a SQLite database. It also uses Unity for dependency injection much like you would in Asp.NET MVC. Within the project, you&#8217;ll find an AppService interface used to provide the definition for simple &#8216;business&#8217; functionality. This is meant to be generic for the sample; but in a real application, I would breakdown the services by functional purpose. They all can share the same LinqRepository data interface, which provides basic rules for LINQ-based CRUD. SubSonic3 hooks right into that and is nearly transparent to the application with the exception of a few attributes on the domain objects. There are some placeholder Mock classes there and sample mappings in the code just for show.</p>
<p><a href="/resources/p773/SubSonicDemo.zip">Download the sample project</a></p>
<p>You can also get the latest version from <a href="http://github.com/nathanb/iws-snippets">IWS Snippets project</a> subversion.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2010/08/subsonic3-works-on-mono/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Simple Linq to Sql Enhancements with T4 Templating</title>
		<link>http://www.integratedwebsystems.com/2009/10/simple-linq-to-sql-enhancements-with-t4-templating/</link>
		<comments>http://www.integratedwebsystems.com/2009/10/simple-linq-to-sql-enhancements-with-t4-templating/#comments</comments>
		<pubDate>Fri, 23 Oct 2009 16:15:15 +0000</pubDate>
		<dc:creator>Nathan</dc:creator>
				<category><![CDATA[T4]]></category>
		<category><![CDATA[Linq to Sql Classes]]></category>
		<category><![CDATA[Sql Server]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.integratedwebsystems.com/?p=373</guid>
		<description><![CDATA[I sometimes underestimate the power of the tools that come with visual...]]></description>
			<content:encoded><![CDATA[<p>I sometimes underestimate the power of the tools that come with visual studio. Usually this is because I&#8217;m ignorant of the fact they even exist until I see them used or read about them somewhere else. <a href="http://www.olegsych.com/2007/12/text-template-transformation-toolkit/" target="_blank">T4 text generation</a> is no exception.  This is a very useful tool that&#8217;s built right into Visual Studio 2008 which I discovered while peeking at the new <a href="http://www.subsonicproject.com" target="_blank">SubSonic 3</a> code when it came out. (Thanks <a href="http://blog.wekeroad.com/" target="_blank">Conery</a>). <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>After spending a day drilling into T4 and learning how it works, I have to say that it was definitely time not wasted. I&#8217;ve since used it for tons of miscellaneous code generation projects including mostly data layer extensions. And with the help of the data provider specific templates in the SubSonic project, much of the schema extraction code has been provided for us through open source.</p>
<p>I&#8217;m a big fan of SubSonic, and I like to push it in all the shops I work with that aren&#8217;t already anchored down to another data framework. However, sometimes we still have to fall back to vanilla data layers like Linq to Sql (L2S), Entity Framework (EF), or straight up ADO.Net depending on the shop and its personalities. Having experience using SubSonic opens your eyes to some useful ways you can improve L2S and the others.</p>
<p><span id="more-373"></span>Like, for example, updating data&#8230; Have you been in a situation (like a web form postback or a web service call) where you&#8217;re instantiating a new entity instance whose data already exists in your database and you need to simply update it?  In L2S, this isn&#8217;t very straight forward. If you don&#8217;t want to mess with detaching and reattaching data entities, you can simple load an instance from the data context and update its fields with the new data; then commit the change back to the data context.</p>
<p>Well that&#8217;s great and all, but who&#8217;s going to type all the load functions? Not me, I hate typing. <img src='http://www.integratedwebsystems.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' />   So T4 comes to the rescue.  Here you&#8217;ll see a simple script that looks at a database and generates LoadFromExisting() functions for each table into a partial class that extends the original L2S class. Then anytime the schema changes, you simply run the T4 template and it re-executes your generation code.</p>
<h3>Using the Generated Code</h3>
<p>Here’s an example helper save function using Linq to Sql.  It simply checks for an existing record. If it exists, it updates its fields with the ones you passed in making it dirty to the data context, or it instructs the data context to insert it as a new one.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public void SaveSection(Section section)
{
    var data = this.GetSectionByID(section.ID);

    if (data == null)
    {
        data = section;
        _DB.Sections.InsertOnSubmit(data);
    }
    else
        data.LoadFromExisting(section);

    _DB.SubmitChanges();
}</pre>
<p>Here is the corresponding LoadFromExisting() definition. You can see it’s very simple. All I really want to do here is update the values and flag the fields on the instance we pulled from the data context as dirty. The main thing to note here is that the class definition is partial.  It matches the namespace and name of the class generated in our DBML data context file.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">public partial class Section
{

    public Section LoadFromExisting(Model.Section data)
    {
        this.ID = data.ID;
        this.DefaultContentID = data.DefaultContentID;
        this.Description = data.Description;
        return this;
    }

}</pre>
<h3>Now for Actually Generating Code with T4</h3>
<p>To briefly explain T4, it’s basically a .net virtual machine hosted by visual studio. The code files appear a lot like classic ASP and MVC where you have rendered sections and functional sections. In T4, the token used to start and end a code section is: &lt;# #&gt;.  Like asp, you can include other files to re-use code files. Those files in this example have the ttinclude extension. Normal T4 scripts must end with the “.tt” extension.</p>
<p>Since we’re using what has already been setup for us by the SubSonic templates, we’re re-using their shared files: <em>Settings.ttinclude</em> and<em> SqlServer.ttinclude</em>. The <em>settings.ttinclude </em>file has all your basic shared settings like the global directives, includes, references, and supporting object model for the database structures. The <em>SqlServer.ttinclude </em>file contains the Sql Server specific schema extraction functions.</p>
<p><a href="http://www.integratedwebsystems.com/wp-content/uploads/2009/10/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" src="http://www.integratedwebsystems.com/wp-content/uploads/2009/10/image_thumb.png" border="0" alt="image" width="185" height="103" align="right" /></a> Add both these files to your project, and then add a new text file with extension “.tt” to your project.  Copy the content from template.tt into your new tt file. The template content simply includes the shared files for you. Notice every time you save this file, it re-runs itself; so be very aware when you’re saving to avoid running the code accidentally.</p>
<p>Here’s the full script for the partial extension:</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">&lt;#@ template language="C#v3.5" debug="True" hostspecific="True" #&gt;
&lt;#@ include file="SQLServer.ttinclude" #&gt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Collections;
using System.ComponentModel;
using System.Data.Common;

namespace &lt;#=Namespace #&gt;
{
&lt;#

    var tables = LoadTables();

    foreach(Table tbl in tables)
    {
        if(!ExcludeTables.Contains(tbl.Name) &amp;&amp; !tbl.Name.StartsWith("aspnet"))
        {
#&gt;

    /// &lt;summary&gt;
    /// A class which represents the &lt;#=tbl.Name #&gt; table in the &lt;#=DatabaseName#&gt; Database.
    /// &lt;/summary&gt;
    public partial class &lt;#=tbl.ClassName#&gt;
    {

            public &lt;#=tbl.ClassName #&gt; LoadFromExisting(Model.&lt;#=tbl.ClassName #&gt; data)
            {
&lt;#
            foreach(Column col in tbl.Columns)
            {

                if (tbl.ClassName == col.CleanName)
                {
                    col.CleanName += "X";
                }
#&gt;
                this.&lt;#=col.CleanName #&gt; = data.&lt;#=col.CleanName #&gt;;
&lt;#
            }
#&gt;
                return this;
            }

        }
&lt;#
   }
  }
#&gt;
}</pre>
<p>So as  you can see, it’s very straight forward.  Here, we’re loading up all the tables, spinning through each one and then writing a function that spins its columns to generate assignment expressions.  (this.&lt;#=col.CleanName #&gt; = data.&lt;#=col.CleanName #&gt;; )  You’ll notice a few variable names being used like “Namespace” or ExcludeTables, etc.  With T4, you have to pretend that anything defined in a global scope is really just a member of this virtual class we created as our script. Those names were actually defined earlier in the Settings.ttinclude.  That is also where we’re setting our connection string name for the connection info. It uses the app.config in current project so you don’t have to save it statically in the file, which is another perk of these SubSonic templates.</p>
<p>For partial classes to work, you have to match the namespace and class name in your partial file. This is extremely useful, because I can generate code all day long with this file and then create yet another partial extension for the the more functional fine detail extensions.</p>
<h3>Enum Generator</h3>
<p>Here’s a nice little enum generator I wrote the other day. We typically use lookup tables in a lot of our projects whose names and values match what we have in our tables. This script uses a global list of table names in the <em>Settings.ttinclude </em>file and selects their data to generate enum code with values. The table structure is: (ID int, Name varchar(50), Description varchar(100)). You’ll need to create the table and fill it with your enumeration data first. Then run this script.</p>
<pre class="brush: csharp; gutter: false; toolbar: false;">&lt;#@ template language="C#v3.5" debug="True" hostspecific="True" #&gt;
&lt;#@ include file="SQLServer.ttinclude" #&gt;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Linq.Expressions;
using System.Collections;
using System.ComponentModel;
using System.Data.Common;

namespace &lt;#=EnumNamespace #&gt;
{
&lt;#
            var list = GetEnums();
            foreach (KeyValuePair&lt;string, List&lt;EnumValue&gt;&gt; pair in list)
            {

            #&gt;

        /// &lt;summary&gt;
        /// An enumeration that represents the table &lt;#= pair.Key #&gt; in database: &lt;#= DatabaseName #&gt;
        /// &lt;/summary&gt;
        public enum &lt;#=pair.Key#&gt;
        {
&lt;#            int counter = 0;
            foreach(var value in pair.Value)
            {
                counter++;
                if (!string.IsNullOrEmpty(value.Description)) {#&gt;
            /// &lt;summary&gt;
            /// &lt;#= value.Description #&gt;
            /// &lt;/summary&gt;
&lt;# } #&gt;            &lt;#= value.Name #&gt; = &lt;#= value.Value #&gt;&lt;#if (counter &lt; pair.Value.Count) {#&gt;,&lt;#}#&gt;

&lt;#            }#&gt;
        }

&lt;#            }#&gt;
}</pre>
<p>In my case, I dropped these enumerations into a custom namespace since the names were shared with the entities representing the tables.  If you wanted to, you could easily drop these into a class as well.</p>
<h3>Download</h3>
<p><a href="/t4.zip" target="_blank">Here’s the zip file containing the four scripts</a>.</p>
<p><em>Disclaimer/Licensing: All code provided here was derived using some of the code in SubSonic templates; hence, this code is open source under the same license. New BSD, which I&#8217;ve included in the downloadable archive. </em></p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.integratedwebsystems.com/2009/10/simple-linq-to-sql-enhancements-with-t4-templating/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

