Monday, June 28, 2010

Quick Script to Create Constants from All Columns Names

One thing I like to do in all my apps is create a static class that holds constants for all Column/Property names. This just avoids messing up names in places where I need to use strings. This is particularly useful when checking that attributes have been applied.

select 
     'public const string ' + COLUMN_NAME + ' = "' + COLUMN_NAME + '";'
from INFORMATION_SCHEMA.COLUMNS
where table_Name in ('Agencies', 'Customers')
group by COLUMN_NAME
order by COLUMN_NAME

The code produced looks like this:

public static class ColumnNames
{
    public const string AgencyName = "AgencyName";
    public const string CustomerName = "CustomerName";
}

I can then refer to the name using something like

VerifyPropertyHasAttribute(ColumnName.AgencyName, typeof(RequiredAttribute));

No comments: