.TT files and property names

This is the second post of http://msprogrammer.serviciipeweb.ro/2012/07/09/tt-files/

Now I will show how .tt files helps you for sorting .

In many WebInterfaces you do present to the user an array of items – a list – and the user can sort after various fields. Let’s make an example:

You have an EmployeeViewModel class that have FirstName, LastName and DepartmentName ( take note that is an EmployeeViewModel that must show to the user the Department name too – and is not the Employee class that have a reference to the table Employee).

Usually, for loading easily the EmployeeViewModel you do create a view in database with the same columns as the names of the properties (FirstName, LastName and DepartmentName)

Now, how you sort after FirstName, LastName and DepartmentName  WITHOUT hardcoding the strings ?( Why hardcoding is not good: the modification are not catch at compile time, but at runtime – and can be hidden)

.TT files to the rescue:

Starting of this class


public partial class EmployeeViewModel
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string DepartmentName { get; set; }

I generate , with classFieldNames.tt , this:


public partial class EmployeeViewModel
        public static FieldNames fieldNames= new FieldNames();
        public class FieldNames{
                public  string FirstName ="FirstName";
                public  string LastName ="LastName";
                public  string DepartmentName ="DepartmentName";

And now in the code is that:


 var field = EmployeeViewModel.fieldNames.DepartmentName;

this is the code for TT_FieldNames. Enjoy!