Simple SQL Server Script For Generating NHibernate Classes/Mappings
With the growing popularity of Fluent NHibernate, mapping files are being used less and less. However if you are using HBM/XML mapping files I recently dug up an old SQL script (originally written by my colleague Alan Lai, since modified slightly by myself) which might help. The SQL Script basically generates some mapping/public property fields from an existing database that you can manually copy around into you application to save you some keystrokes.
Disclaimer: While helpful, this script is pretty simple and only handles basic properties (no keys, relationships, etc). Still, I think it’s pretty cool and it would be selfish of me not to share it with the NHibernate world :)
The SQL Script
Basically the script uses the sysobjects, syscolumns, and systypes tables to inspect a database and generate a row for each table/column. Take a look at the entire script:
SELECT table_name=sysobjects.name,
column_name=syscolumns.name,
'<property name="' + syscolumns.name + '" column="' + syscolumns.name + '" />' as mapping,
'public virtual ' +
cast (case
when systypes.name in ('varchar', 'nvarchar') then 'string'
when systypes.name = 'bit' then 'bool'
when systypes.name = 'datetime' then 'DateTime'
else systypes.name
end as varchar(10)) + ' ' + syscolumns.name + ' { get; set; }' as property,
datatype=systypes.name,
length=syscolumns.length
FROM sysobjects
JOIN syscolumns ON sysobjects.id = syscolumns.id
JOIN systypes ON syscolumns.xtype=systypes.xtype
WHERE sysobjects.xtype='U' AND systypes.name <> 'sysname'
ORDER BY sysobjects.name,syscolumns.colid
The Results
Running the script on the beloved Northwind database generates 133 rows, a few of which I will reproduce below:
Now you can open up Customers.hbm.xml and copy in the properties under the mapping column, and in Customers.cs you can do the same using the values in the property column.
Hopefully this will save you some typing if you are using NHibernate mapping files and starting from an existing database. Enjoy!