Created
February 22, 2017 15:49
-
-
Save aburok/1d9bdb1120b590f3149f33bfd9699a31 to your computer and use it in GitHub Desktop.
Generate c# const string class with SQL Server table and column names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<#@ template debug="false" hostspecific="false" language="C#" #> | |
<#@ assembly name="System.Core" #> | |
<#@ import namespace="System.Linq" #> | |
<#@ import namespace="System.Text" #> | |
<#@ import namespace="System.Collections.Generic" #> | |
<#@ output extension=".cs" #> | |
<#@ assembly name = "Microsoft.CSharp" #> | |
<#@ assembly name = "System.Data" #> | |
<#@ import namespace = "System.Dynamic" #> | |
<#@ import namespace = "System.Data.SqlClient" #> | |
<# | |
var namespaceName = "Application.Common"; | |
// Update the connection string to something appropriate | |
var connectionString = @"<<<Connection String>>>"; | |
#> | |
<# | |
using (var db = new SqlConnection (connectionString)) | |
using (var cmd = db.CreateCommand ()) | |
{ | |
db.Open(); | |
var tables = ReadRows (cmd, "SELECT * FROM sys.tables").ToArray (); | |
var columns = ReadRows (cmd, "SELECT * FROM sys.columns").ToLookup (k => k.object_id); | |
#> | |
// ReSharper disable InconsistentNaming | |
// ReSharper disable MemberHidesStaticFromOuterClass | |
namespace <#=namespaceName#> | |
{ | |
// For shorter names in code this is class names is shorter | |
public static class DbConsts | |
{ | |
<# | |
foreach (var table in tables) | |
{ | |
#> | |
public static class <#=table.name#> | |
{ | |
public const string Name = "<#=table.name#>"; | |
public static class Cols | |
{ | |
<# | |
IEnumerable<dynamic> tc = columns[table.object_id]; | |
var tableColumns = tc.OrderBy (r => r.column_id).ToArray (); | |
foreach (var tableColumn in tableColumns) | |
{ | |
#> | |
public const string <#=tableColumn.name#> = "<#=tableColumn.name#>"; | |
<# | |
} | |
#> | |
} | |
} | |
<# | |
} | |
#> | |
} | |
} | |
<# | |
} | |
#> | |
<#+ | |
static IEnumerable<dynamic> ReadRows (SqlCommand command, string sql) | |
{ | |
command.CommandText = sql ?? ""; | |
using (var reader = command.ExecuteReader()) | |
{ | |
while (reader.Read()) | |
{ | |
var dyn = new ExpandoObject (); | |
IDictionary<string, object> dic = dyn; | |
for (var iter = 0; iter < reader.FieldCount; ++iter) | |
{ | |
dic[reader.GetName(iter) ?? ""] = reader.GetValue(iter); | |
} | |
yield return dyn; | |
} | |
} | |
} | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment