Thursday, August 21, 2008

CodeDom NHibernate Mapping File Builder

I am currently watching the 'Summer of NHibernate' videos and have found myself wanting a tool for generating the HBM Mapping file. This was a painful place to be looking at a white screen to hand-fill with XML, as if anybody wants to state again all of the columns and data types already typed into a class and a "Create Table" script.


I have code already in all my other tools for getting database schema into my "columns" typed dataset. I ran XSD.EXE over the HBM file which I built by hand while watching 'Summer of NHibernate' to get a Class for easily authoring the XML document. Populating this class and then Serializing it was a nice way to stay in C# for the whole operation.

So here is what I am starting out of the gate with.



public static string GetMappingFile(SqlConnection Connection, string TableName)
{
string fileName = TableName + "hbm.xml";
hibernatemapping newMapping = new hibernatemapping();
newMapping.@namespace = "Acme.DataLayer";
newMapping.@class = new hibernatemappingClass();

hibernatemappingClass newClass = newMapping.@class;
newClass.name = TableName;
newClass.table = TableName;

Columns cols = PopulateColumns(Connection, TableName, CommandType.TableDirect);
newClass.property = new hibernatemappingClassProperty[cols.Column.Count];

int index = 0;

foreach (Columns.ColumnRow cRow in cols.Column)
{
newClass.property[index] = new hibernatemappingClassProperty();
hibernatemappingClassProperty prop = newClass.property[index];
prop.column = cRow.Column_Name;
prop.name = cRow.Column_Name;
prop.type = cRow.Data_Type;

switch (cRow.Data_Type.ToUpper())
{
case "DECIMAL":
break;
case "INT":
prop.type = "Int32";
break;
case "SMALLINT":
prop.type = "Int32";
break;
case "BIT":
prop.type = "Int32";
break;
case "VARCHAR":
prop.type = "string";
break;
default:
prop.type = "string";
break;
}
index++;
}

System.Xml.Serialization.XmlSerializer xmlSerializer =
new System.Xml.Serialization.XmlSerializer(typeof(hibernatemapping));

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

xmlSerializer.Serialize(sw, newMapping);

return sb.ToString();
}

1 comment:

Anonymous said...

This is great info to know.