Easily Generate Business Objects From The Database

Posted Tuesday, September 23, 2008 11:48 AM by Nathan Zaugg

netdev I know the title of this post is a little bit of a misnomer, business objects will never map 1 to 1 with relational database objects.  However, when just starting out and when you get to control the schema of the database, it sure makes a good starting point and this trick makes it really easy and avoids a lot of typing.  It supports SQL 2005 and SQL 2008.

 

The first step is to download the script. The script I wrote to do this can be found at http://interactiveasp.net/media/p/87.aspx

Once the script has been downloaded, open it in SQL Server Management Studio and fill in the fields for Database name and Table Name.

Set Settings for Property Generation

After the settings are set run the script.  You should get something that looks a lot like:

 

Result Properties

Next, select all of the rows that are part of the table you are creating the class for.  Notice that my selection excludes the first column.  After the rows are selected, copy the rows out of the results grid.  Next, open up your project in Visual Studio.  Create a new class with the appropriate name and paste the contents of the clipboard as shown below.

Paste copied Code

The act of pasting the code into a class will cause the code to be formatted.  This should create nice looking properties inside of your class.

Newly Created Class

And that is all there is to it.  You will notice that by default the properties are sorted first by data type (desc), then by column name.  You can change this sort by changing the SQL Script if you wish.  I tend to like to group like-types together and then alphabetize.  I think it makes it a little more readable.  Also, we are using auto-implemented properties (aka Automatic Properties).

 

If you use the script or have comments / suggestions, please leave a comment and let me know!

Links