Saturday, 21 January 2012

Generate class code based on SQL table definition

I was looking for a quick way to generate the boilerplate code for a class based on the definition of a table in my SQL database. I recently started researching the various ORM offerings, but it's still quite early days and I'm looking for something simple that I can use in the meantime to help speed things up.

It dawned on me that I should be able to generate the code within SQL itself using the INFORMATION_SCHEMA.COLUMNS data of the table.

Below is a stored procedure that generates the VB code for a class based on a database table specified in the first parameter. Use the second parameter to specify the name of the class, or leave it as NULL for the Stored Procedure to assume that your table name is pluralised with an "s", therefore naming the class the same less the "s".

I'm using the wonderful little AutoMapper library in the generated code to automatically map the columns from the SQL query to the fields of the class. When I think of it, I'm trying to do for our class code what AutoMapper is doing for object-object mapping code - both of which are "rather dreary and boring to write".

As I got going with this, I realised that I needn't stop at the domain object class code. I'm also outputting the code for a backing repository class that does the database interaction and the code for a default unit test to check that the database retrieve works. I'm not claiming to be properly using the Repository Pattern here, I just think the term repository is appropriate. And it's more of an integration test than a unit test.

The SQL Stored Procedure code:



Execute the Stored Procedure and perform a bit of Copy-Paste Driven Development. If I get the team using this, then it also has the nice side affect of applying a standard coding pattern to our classes.

A quick and simple solution - no installation required!

No comments:

Post a Comment