Add Column on the fly.


I have a need to add 'custom' DatabaseColumns to DatabaseTables. The custom columns are used to generate poco class readonly calculated property columns. The issue is that when I add a new column, I cannot set the DataType. The code sets the datatype on the dbread and, looking at the code, I can't find a good way to do this. All other properties are fine, but the DataType / NetDataType present a problem. Is there a way to do this?

BTW: I haven't fully tested the Database Object Comparer, but so far, it to be exactly what I needed. Thanks!
Closed Dec 14, 2013 at 9:48 AM by Martinjw
See explanation


Martinjw wrote Sep 4, 2013 at 6:33 AM

When we read the database schema, we get a string value for the column type - e.g. "VARCHAR".
We assign this to the property column.DbDataType.

To get the .net datatype, the codegen uses the column.DataType property.
The full schema read gives us a list of types - schema.DataTypes - which contains the database type name - e.g. "VARCHAR" - and the .Net type - "string". So the column.DataType links to one of the schema.DataTypes.

If you just set the column.DbDataType you can call DatabaseSchemaFixer.UpdateDataTypes(schema), and it links up the correct column.DataType for you (it doesn't overwrite any existing ones, so it's safe to do repeatedly).
Manually the logic is simply to loop through the schema.DataTypes to find the TypeName that matches the DbDataType, then assign that to column.DataType.

In the tests, you'll see examples where we set the column with it's datatype in lines like this:
table.AddColumn("Surname", "NVARCHAR");
table.AddColumn("FirstName", DbType.String);
Followed by a call to DatabaseSchemaFixer.UpdateDataTypes(schema)
Internally there's a DataTypeMappingFactory which creates a DataTypeMapper for each database type (SqlServer, Oracle, etc), so simple types (string, DbTypes) get translated to the correct database type ("NVARCHAR").
These fluent extension methods can make adding ad hoc columns very simple.