How-to: Rename your generated CSLA property names

In the following example, I'll show you how to use the CodeSmith CSLA template's powerful renaming options. Many of you might have a legacy database with those ugly prefixes, or things you wish you could refactor but just can't. Luckily, you're in luck as CodeSmith is going to save the day once again! By default we will strip any invalid characters from your property names like prefixed digits etc... Please note that these methods also work for renaming class names, but there are other methods that we will cover later that are is the recommended way to specify a class name.

In this example, I'm going to be renaming column names in the following database table:

CREATE TABLE [dbo].[Rename](
	[RenameID] [int] NOT NULL,
	[RenameName] [nvarchar](50) NOT NULL,
	[RenameA] [nvarchar](50) NOT NULL,
	[Name] [nvarchar](50) NOT NULL,
	[RenameAge] [int] NOT NULL,
 CONSTRAINT [PK_Rename] PRIMARY KEY CLUSTERED 
(
	[RenameID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

As you can see this would cover a few use cases when it comes to legacy database tables. By default when this is generated the code will look like this. Please note that all code has been simplified to show the results only.

C#

public System.Int32 RenameID { get; set; }

public System.String RenameName { get; set; }

public System.String RenameA { get; set; }

public System.String Name { get; set; }

public System.Int32 RenameAge { get; set; }

Visual Basic

Public Property RenameID() As System.Int32
End Property

Public Property RenameName() As System.String
End Property

Public Property RenameA() As System.String
End Property

Public Property Name() As System.String
End Property

Public Property RenameAge() As System.Int32
End Property

As you can see the name's haven't changed at all. I'll now show you how to rename the property names! 

Method 1

This method can be a lot of work, but for renaming a few columns is the quickest and easiest way to rename property names. Inside of the CSLA Template folder, there will be a folder called Common. Open this folder and double click on the KeywordRenameAlias file. In the future, we would like to make this a per project setting as this method renames everything generated by the templates. To create a per project setting use a different method or create a copy of the templates for a specific project.

I'm going to show you how to quickly rename the RenameAge column to Age and the RenameA column to Location. As you can see there are already a few existing entries. Well add the two entries and then hit the save icon. Then we will go back and regenerate.

The generated code will be updated with our new names!

C#

public System.Int32 RenameID { get; set; }

public System.String RenameName { get; set; }

public System.String Location{ get; set; }

public System.String Name { get; set; }

public System.Int32 Age { get; set; }

Visual Basic

Public Property RenameID() As System.Int32
End Property

Public Property RenameName() As System.String
End Property

Public Property Location() As System.String
End Property

Public Property Name() As System.String
End Property

Public Property Age() As System.Int32
End Property
We will now revert the KeywordRenameAlias mapping file back to it's default values.

Method 2

This method works much like Method one, instead your settings are stored as extended properties inside of SQL Server. We will open SQL Management Studio and right click on the column in question and select properties. Then we will add an extended property called CS_Alias with the value being the desired name.

SQL

EXEC sys.sp_addextendedproperty @name=N'CS_Alias', @value=N'Location' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'Rename', @level2type=N'COLUMN',@level2name=N'RenameA'
GO

Method 3

This method is very powerful and could save you a bunch of time! However, it currently requires you to open up the source solution located in the Source folder, make one change and recompile. We will make this much easier to do in a later version. Inside of the CodeSmith.SchemaHelper Project, open up the Configuration class. Then find the following line:

NamingProperty = new NamingProperty
    {
        EntityNaming = EntityNaming.Singular,
        TableNaming = TableNaming.Mixed,
        ColumnNaming = ColumnNaming.Preserve
    };

You will want to change the ColumnNaming value to this:

NamingProperty = new NamingProperty
    {
        EntityNaming = EntityNaming.Singular,
        TableNaming = TableNaming.Mixed,
        ColumnNaming = ColumnNaming.RemoveTablePrefix
    };

When ColumnNaming is set to RemoveTablePrefix, sit back and be amazed at how much cleaner your properties become automatically! When this is set, Method 1 and Method 2 will run and take preference. After Method 1 or Method 2 run, if the property name matches the cleaned table name and the renaming character length is greater than one character(for uniqueness) then we will strip the table name from the property name, then rerun Method 1 and Method 2. Please note: any association names will not be renamed via this method.

After regenerating, your properties should look something like this:

C#

public System.Int32 Identification { get; set; }

public System.String Name1 { get; set; }

public System.String RenameA { get; set; }

public System.String Name2 { get; set; }

public System.Int32 Age { get; set; }

Visual Basic

Public Property Identification() As System.Int32
End Property

Public Property Name1() As System.String
End Property

Public Property RenameA() As System.String
End Property

Public Property Name2 () As System.String
End Property

Public Property Age() As System.Int32
End Property
You might be wondering why RenameID was changed into Identification. This is because the table prefix was stripped leaving ID, ID is predefined in Method 1 by default, and thus was renamed to Identification. As you can see if your column name is RenameA, then you will need to use Method 1 or Method 2 as we won't rename anything with this method that would result in a really short name.
Don't worry, we didn't change the generated stored procedures or parameterized Sql column names because of these methods!!!

C#

const string commandText = "INSERT INTO [dbo].[Rename] ([RenameID], [RenameName], [RenameA], [Name], [RenameAge]) VALUES (@p_RenameID, @p_RenameName, @p_RenameA, @p_Name, @p_RenameAge)";
using (SqlConnection connection = new SqlConnection(ADOHelper.ConnectionString))
{
    connection.Open();
    using(SqlCommand command = new SqlCommand(commandText, connection))
    {
        command.Parameters.AddWithValue("@p_RenameID", this.Identification);
		command.Parameters.AddWithValue("@p_RenameName", this.Name1);
		command.Parameters.AddWithValue("@p_RenameA", this.RenameA);
		command.Parameters.AddWithValue("@p_Name", this.Name2);
		command.Parameters.AddWithValue("@p_RenameAge", this.Age);

        //result: The number of rows changed, inserted, or deleted. -1 for select statements; 0 if no rows were affected, or the statement failed. 
        int result = command.ExecuteNonQuery();
        if (result == 0)
            throw new DBConcurrencyException("The entity is out of date on the client. Please update the entity and try again. This could also be thrown if the sql statement failed to execute.");

        LoadProperty(_originalIdentificationProperty, this.Identification);
    }
}

Visual Basic

Const commandText As String = "INSERT INTO [dbo].[Rename] ([RenameID], [RenameName], [RenameA], [Name], [RenameAge]) VALUES (@p_RenameID, @p_RenameName, @p_RenameA, @p_Name, @p_RenameAge)"
Using connection As New SqlConnection(ADOHelper.ConnectionString)
    connection.Open()
    Using command As New SqlCommand(commandText, connection)
        command.Parameters.AddWithValue("@p_RenameID", Me.Identification)
	command.Parameters.AddWithValue("@p_RenameName", Me.Name1)
	command.Parameters.AddWithValue("@p_RenameA", Me.RenameA)
	command.Parameters.AddWithValue("@p_Name", Me.Name2)
	command.Parameters.AddWithValue("@p_RenameAge", Me.Age)
    
        'result: The number of rows changed, inserted, or deleted. -1 for select statements; 0 if no rows were affected, or the statement failed. 
        Dim result As Integer = command.ExecuteNonQuery()
        If (result = 0) Then
            throw new DBConcurrencyException("The entity is out of date on the client. Please update the entity and try again. This could also be thrown if the sql statement failed to execute.")
        End If
    End Using
    
    LoadProperty(_originalIdentificationProperty, Me.Identification)
    
End Using

Posted Aug 03 2010, 02:03 AM by Blake Niemyjski |
Filed under: , ,
windowscoding.com;
Copyright © 2008 Windows Coding
Microsoft and Microsoft logo's are trademarks of Microsoft Corporation.