次の方法で共有


Interesting Rename Refactoring Scenarios: Coalescing Two or More Objects

Here is another interesting use case for rename refactoring – coalescing two or more objects. What do I mean by that?

 

Well, this one is slightly different from what would traditionally be considered rename refactoring. It smells more like a semi-automated Merge Tables database refactoring.

 

Let’s say the scenario here is that you have a [dbo].[Contacts] table and a [dbo].[ContactPhotos] table. Both tables are keyed on ContactID. You may realize that you always end up joining these tables and thus wish to merge the ContactPhotos table with the Contacts table.

 

Let’s say the table definitions for these objects are as follows:

CREATE TABLE [dbo].[Contacts]

(

      ContactID int NOT NULL,

      FirstName varchar(100) NOT NULL,

      MiddleName varchar(100) NULL,

      LastName varchar(100) NOT NULL,

      BirthDate datetime NULL,

      SSN varchar(50) NOT NULL,

);

 

CREATE TABLE [dbo].[ContactPhotos]

(

      ContactID int NOT NULL,

      ContactPhoto image NULL

);

 

To simplify this task, you can use rename refactoring to get you most of the way. Just follow these steps:

 

  1. Copy the appropriate column definitions from the [dbo].[ContactPhotos] table to the [dbo].[Contacts] table. In our case, this is simply the [ContactPhoto] column.

  2. Use Rename Refactoring to rename [dbo].[ContactPhotos] to [dbo].[Contacts]. You will be warned that the [dbo].[Contacts] object already exists. Simply say Yes to continue. You will then be shown a list of all the references that will be updated. The beauty of using rename refactoring in this way is that we automatically find all references to [Contact Photos] and update those references to now point to [Contacts].

  3. Delete the now un-needed old [dbo].[ContactPhotos] file from Solution Explorer.

  4. Simplify queries. Clearly many queries will need to be updated to remove joins where they are now unnecessary. You can view the refactoring log file to see a list of all the places that the ContactPhotos table was referenced and review and update them if appropriate.

     

In upcoming CTP6 you will be able to leverage this feature exactly as described above. So check it out!

 

Sachin Rekhi