How do I create my own code generation tool in Visual Studio 2010?

I just want to create a class with attributes that come from a database table .

If I have a database table like below:

+-------------------+
| Id | Name         |
+----+--------------+
| 1  + foo          |
| 2  + hello.world  |
| 3  + null         |
+-------------------+

      

I would like to autogenerate class

that looks like this:

class MyTable {
  public static int Foo = 1;
  public static int HelloWorld = 1;
  // null was omitted for Id = 3
}

      

+3


source to share


3 answers


You can use T4 transform to get the job done. Use "Add New Item" and "Text Template".

The T4 language is a way of using C # code to generate C # code. Most of the texts are parsed directly into the output file, and new code can be written inside the <#

and tags #>

. The file starts with wrapped imports and using operators, so a very simple pattern could be something like this:

   <#@ template debug="false" hostspecific="false" language="C#" #>
   <#@ import namespace="System.Data" #>
   <#@ import namespace="System.Data.SqlClient" #>
   <#@ assembly name="System.Data" #>

   namespace Some.Namespace
   {
       public class TestClass 
       {
    <# 

    using(var cnn = new SqlConnection(@"server=.\sqlexpress;Integrated Security=SSPI;Database=ApplicationManagement"))
    {
        cnn.Open();
        var cmd = new SqlCommand("SELECT TextKey, TextValue FROM TblBrandingKeyValues WHERE BrandingIdentifier = 'Default'", cnn);

        var reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            var defaultText = reader.GetString(1);
            var name = reader.GetString(0);


    #>
    public string <#= name #> 
    {
        get { return "<#= defaultText #>"; } 
    }

    <#
        }
    }

     #>

    }
}

      



} <# @output extension = ".cs" #>

This template will create a class TestClass

with a set of read-only properties retrieved from a database table TblBrandingKeyValues

.

I would recommend these T4 tutorials .

+4


source


if you want to create your own tool, you better take a look at System.CodeDom

the namespace which contains everything you need to generate code. Of course you need to code the algorithm that generates the class.

more information in the link below:



http://msdn.microsoft.com/en-us/library/ms404245.aspx

In any case, remember that .NET already offers many "built-in" tools / namespaces that do exactly the same thing (for example, using the Entity Framework).

0


source


Use T4 Templates . I am generating many classes this way.

0


source







All Articles