How to find NHibernate entity table mapping from an object type?

Once I have mapped my domain in NHibernate, how can I cancel the search for these mappings somewhere else in my code?

Example:

For some reason, the Pony object is mapped to a table named "AAZF1203". (Stupid database table names are obsolete!) I want to find out this table name from NH mappings using only typeof(Pony) , because I need to write the query elsewhere.

How to make the next test pass?

 private const string LegacyPonyTableName = "AAZF1203"; [Test] public void MakeSureThatThePonyEntityIsMappedToCorrectTable() { string ponyTable = GetNHibernateTableMappingFor(typeof(Pony)); Assert.AreEqual(LegacyPonyTableName, ponyTable); } 

In other words, what should GetNHibernateTableMappingFor(Type t) look like?

+6
c # nhibernate nhibernate-mapping
source share
2 answers

At what point do you need this information?

Because it depends on what you have ...

I recently 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 can also get it from a session ...

 ((ILockable)session.GetSessionImplementation() .GetEntityPersister(null, new Pony())).RootTableName 
+12
source share

I found this to work to get the name of the table where the objects are stored.

  • You must have an instance of NHibernate.Cfg.Configuration
  • You are requesting an instance of NHibernate.Mapping.Table for this constant type.
  • The Name property of the Table instance corresponds to the name of the table in which the objects are stored.

See 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; 

It can be wrapped in such a function.

 public static String GetTableName<T>(NHibernate.Cfg.Configuration config) { return config.GetClassMapping(typeof(T)).RootTable.Name; } 

NOTE: Strange, the Catalog and Schema of the NHibernate.Mapping.Table` properties do not matter. At least not in my case.

+2
source share

All Articles