How to view table column metadata using NHibernate?

How can I list the column metadata ( IColumnMetadata ) of a table using NHibernate in "any" database?

ITableMetadata contains only GetColumnMetadata() , where I need to provide columnName . IDataBaseSchema contains GetColumns() , which returns a plain DataTable . I found a GetColumnName() on AbstractTableMetadata method that I could use, but it is protected and not contained in ITableMetadata . Any reason for this?

How is this API intended to be used?

+4
source share
2 answers

Suppose you can use Configuration.ClassMappings to get a list of mapped classes. Each of them will have the Table property, which in turn has the ColumnIterator property. You should be able to get a list of column names.

0
source

You're right. ITableMetadata does not expand the column names in the table. It seems that classes were designed for use with mapping files that explicitly specify column names. However, if you take a quick look at Reflector, you will find that all column names are actually stored in a private variable in the AbstractTableMetadata class (from which all ITableMetadata implementations are derived.

Here is the code to extract all column names from all tables in the database:

 var dialect = sess.GetSessionImplementation().Factory.Dialect; var dbSchema = dialect.GetDataBaseSchema(sess.Connection as DbConnection); foreach (DataRow row in (sess.Connection as DbConnection).GetSchema("Tables").Rows) { ITableMetadata md = dbSchema.GetTableMetadata(row, false); var hiddenColumnsProperty = typeof(AbstractTableMetadata).GetField("columns", BindingFlags.NonPublic | BindingFlags.Instance); var columns = hiddenColumnsProperty.GetValue(md) as Dictionary<string, IColumnMetadata>; foreach (var colName in columns.Keys) { Console.WriteLine(md.Name+"."+colName); } } 
0
source

Source: https://habr.com/ru/post/1383112/


All Articles