Once I've mapped my domain in NHibernate, how can I reverse lookup those mappings somewhere else in my code?
Example:
The entity Pony
is mapped to a table named "AAZF1203" for some reason. (Stupid legacy database table names!) I want to find out that table name from the NH mappings using only the typeof(Pony)
because I have to write a query elsewhere.
private const string LegacyPonyTableName = "AAZF1203";
[Test]
public void MakeSureThatThePonyEntityIsMappedToCorrectTable()
{
string ponyTable = GetNHibernateTableMappingFor(typeof(Pony));
Assert.AreEqual(LegacyPonyTableName, ponyTable);
}
In other words, what does the GetNHibernateTableMappingFor(Type t)
need to look like?
At which point do you need that information?
Because it depends on what you have...
Not long ago I had to get the table name from an audit event listener, and I used this:
IPostDatabaseOperationEventArgs args //parameter
var tableName = ((ILockable)args.Persister).RootTableName.ToLower();
You could also get it from the session...
((ILockable)session.GetSessionImplementation()
.GetEntityPersister(null, new Pony())).RootTableName
I have found this to work to get the name of the table where the entities are persisted.
NHibernate.Cfg.Configuration
NHibernate.Mapping.Table
for the given persistent type.Name
property of the Table
instance corresponds to the name of the the table where the entities are persisted.See the code below.
NHibernate.Cfg.Configuration config = new Configuration();
/*
The initialisation here like config.AddAssembly(... and so forth
*/
NHibernate.Mapping.Table table = config.GetClassMapping(typeof(T)).RootTable;
String NameOfTableOfInterest = table.Name;
This could be wrapped in a function like so
public static String GetTableName<T>(NHibernate.Cfg.Configuration config)
{
return config.GetClassMapping(typeof(T)).RootTable.Name;
}
NOTE: Strange enough, the properties Catalog
and Schema of the
NHibernate.Mapping.Table` have no value. At least, not in my case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With