Sometime there is need of mapping some values from database to
code level, basically in look up tables.
I am going to generate enum based on database values. In this example, I am going for T4 template to generate up enum by using SqlDataReader.
We can have any SQL query to generate enum. In my case, Privilege code, name and description from table would generate up enum.
I am going to generate enum based on database values. In this example, I am going for T4 template to generate up enum by using SqlDataReader.
We can have any SQL query to generate enum. In my case, Privilege code, name and description from table would generate up enum.
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.Data" #>
<#@ include file="EF.Utility.CS.ttinclude"#>
<#@ import namespace="System.Data.SqlClient" #>
<#
var code = new CodeGenerationTools(this);
var connectString = "Set connection string";
var queryString = "select PrivilegeCode, PrivilegeName, PrivilegeDescription from Privilege";
#>
namespace <#= code.VsNamespaceSuggestion()#>
{
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template and will be overwritten as soon
// as the template is executed.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/// <summary>
/// Different permission rules for users
/// </summary>
public enum PermissionRule
{
<#
using (SqlConnection connection =
new SqlConnection(connectString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
#>
/// <summary>
/// <#=reader[1] #>
/// </summary>
/// <remarks><#=reader[2] #></remarks>
<#=reader[0] #>,
<#
}
reader.Close();
}
#>
}
}
Set connectString variable as desired database connection.
Set queryString to table that you want to connect.
Using those three columns I am able to generate enum having name, comment and remark. Now, if lookup table changes then I just need to do “Run Custom Tool” on template which would generate up new enum values without copying/pasting values on code level.
Comments
Post a Comment