Reputation: 29241
I simply want to generate a class with attributes that comes from a Database table.
If I have a Database table like the following:
+-------------------+
| Id | Name |
+----+--------------+
| 1 + foo |
| 2 + hello.world |
| 3 + null |
+-------------------+
I would like to auto-generate a class
that will looks like the following:
class MyTable {
public static int Foo = 1;
public static int HelloWorld = 1;
// null was omitted for Id = 3
}
Upvotes: 3
Views: 3939
Reputation: 26737
if you want to create your own custom tool you better look at the System.CodeDom
Namespace
which contains all you need for generating code. Of course you have to code the algorithm that generate the class.
more info at the below link:
http://msdn.microsoft.com/en-us/library/ms404245.aspx
Bear in mind anyway that .NET already offers lots of "build-in" tool/namespace that does exactly the same job (for example using Entity Framework)
Upvotes: 0
Reputation: 15076
You could use a T4 transformation to do the work. Use "Add new item" and "Text template".
The T4 language is a way to use C# code to genarate C# code. Most text is parsed directly to the output file, and new code can be written inside <#
and #>
tags. The file starts with wrapped imports and using statements, so a very simple template could be something like:
<#@ 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 would create a class TestClass
with a set of read only properties retrieved from database table TblBrandingKeyValues
.
I would recommend these T4 tutorials.
Upvotes: 4