Sometimes you need to automate the repetitive task of generating business objects from table schema. This article uses a free tool called CodeSmith to generate domain entity classes (a.k.a. business objects) for
ObjectSpaces from your pre-existing database tables.
ObjectSpaces is a persistence framework that will be available with .NET 2.0. A preview version was distributed at the PDC conference in October 2003. You can also obtain
ObjectSpaces if you have a MSDN subscription.
A persistence layer, like
ObjectSpaces, can simplify your life by dynamically (at runtime) generating the SQL statements that move data between memory and relational tables. That means that you do not write data access code for your business objects. Instead, you create a mapping file that maps the business classes and their properties to relational data tables and columns.
However, at the time I am writing this article, some necessary tools do not yet exist, hence the motivation for this article. One of the time consuming tasks when working with
ObjectSpaces is generating the public properties that wrap the private fields. Besides being good object-oriented programming practice, using a public property to wrap a private field is a requirement for data binding to an
ObjectSet. Therefore, as a policy, I always create my domain classes in this manner.
Using CodeSmith to generate ObjectSpaces entities
First, download the free CodeSmith code generation tool from the CodeSmith site. Run the msi to install it. CodeSmith installs into your Programs menu.
Next, if you are using Microsoft
ObjectSpaces, you will want to download the templates that go along with this article. I have templates for generating both C# and VB.NET business classes for
ObjectSpaces. Extract the two CodeSmith template files into the correct directory where CodeSmith lives. On my machine it goes into c:\Program Files\CodeSmith\Samples\.
Using CodeSmith is simplicity itself. Run the CodeSmith Explorer from your Programs menu.
You can edit the template right from the Explorer by right-clicking on the .cst file and selecting edit. Execute the template/script by double-clicking it. Click the ellipse (...) next to Source Table to bring up the Table Picker. If it gives you an error, then click the ellipse after Data Source to edit the connection string to point to your database. Once you have a table selected, click the Generate button and Whala!, the source code for your business object appears in the Template Output window. Copy and paste this code into your Visual Studio source file. That's it!
Points of Interest
ObjectSpaces team will create integrated Visual Studio Add-ins. In the meantime, tools like CodeSmith will make your life easier.
Initial version - 11/21/2003