Simple TSQL and C# Entity Generator for S#arp Architecture

Recently we started a big project which uses S#arp Architecture and for those who does not know what it is you can go to the site (http://www.sharparchitecture.net/) and have a read, but in a gist it is an open source architectural foundation that uses ASP.NET MVC framework with NHibernate.

The following principles of this architecture are Domain Driven Design Focus, Loosely coupled, Preconfigured Infrastructure and Open Ended Presentation that means having those principles in mind the developer can concentrate more on Domain and User Experince part of the application that is being developed.

Having said that we used this open-source architecture to leverage on its principles and now we are on the first phase of the project where we are building the Domain layer where we define all the entities needed. If you have a big database this will be a tedious task mapping tables and columns to a classes so I created a TSQL script to generate those entities so that I’ll just copy and paste the output to a cs file and were ready to go.

Now let’s go to the queries, you will notice that there is a complex join in how we get our data regarding our data structure which can be easily extracted from the Information Schema, if you are interested on what other items can be extracted from it have a read here
http://msdn.microsoft.com/en-us/library/ms186778.aspx

Once we have the data we need, we start to process it and it’s not that straightforward but its easy all you need to do is to gather information whether a column or field is nullable so that we can declare it as nullabe in the codes. We also need a mapping to SQL DataTypes to .Net Data Types hence the big if conditions.

Also since we are using the S#arp Architecture there is a convention for PrimaryKeys so we don’t need to declare it as it is handled by the PrimaryKeyConvention class under NHibernateMaps\Convention, so if you named your PK right prefixing them with Id then this will be easy but you can always override it if you wanted to. Below is the code that handles it