T4 to generate Enum from SQL Server table values
What I want to achieve is more or less the inverse of this:
http://www.olegsych.com/2008/07/t4-template-for-generating-sql-view-from-csharp-enumeration/
I have a value group table (enum names) and a values table (enum values), and want to turn those into enums. Both are in SQL Server, and both do happen to be in an .edmx (so there would be quite a few ways to read the values).
Is there something "out there" that already does this (and I didn't find it)? If not, what would be the best开发者_JAVA技巧 way to go about reading the data (SMO, EDMX with dynamic loading, ...)
I've put some more effort into writing such a template so it does all these:
- generates enumeration values with explicit integer values;
- uses Visual Studio's namespace naming convention so generated enumerations have project's default namespace with any subfolders appended (just like any code file in Visual Studio);
- adds complete enumeration XML documentation by using additional description table column values; if you don't have these never mind;
- correctly names the generated file and adds an additional attribute in the code so the generated
enum
doesn't get scrutinised by code analysis; - multi-word lookup table values are correctly concatenated to pascal-cased equivalents (ie. Multi word value becomes a
MultiWordValue
); - enumeration values always start with a letter;
- all enumeration values consist of only letters and numbers, everything else gets cut out;
Anyway. Everything is very well documented in this blog post.
Ok, here's how I implemented it:
- Use VolatileAssembly from the T4 Toolbox to reference an assembly that...
- Implements a T4 Helper class that does all the database work (when using EF, make sure to use a connection string when instantiating the context)
- In the .tt, simply call into the T4 helper class to get the data you need and create your class(es)
精彩评论