tags:

views:

32

answers:

2

Suppose I have a class Customer that is mapped to the database and everything is a-ok.

Now suppose that I want to retrieve - in my application - the column name that NH knows Customer.FirstName maps to.

How would I do this?

A: 

I'm not aware that that's doable.

I believe your best bet would be to use .xml files to do the mapping, package them together with the application and read the contents at runtime. I am not aware of an API which allows you to query hibernate annotations (pardon the Java lingo) at runtime, and that's what you would need.

Update: Judging by Jamie's solution, NHibernate and Hibernate have different APIs, because the Hibernate org.hibernate.Hibernate class provides no way to access a "configuration" property.

Tomislav Nakic-Alfirevic
+2  A: 

You can access the database field name through NHibernate.Cfg.Configuration:

// cfg is NHibernate.Cfg.Configuration
// You will have to provide the complete namespace for Customer
var persistentClass = cfg.GetClassMapping(typeof(Customer));
var property = persistentClass.GetProperty("FirstName");
var columnIterator = property.ColumnIterator;

The ColumnIterator property returns IEnumerable<NHibernate.Mapping.ISelectable>. In almost all cases properties are mapped to a single column so the column name can be found using property.ColumnInterator.ElementAt(0).Text.

Jamie Ide
I might be mistaken on this but I believe that it is also possible by querying some of the methods on the persister for the type. You can get the persister from the factory
George Mauer
You can get a lot of info about the object from the persister but I could not find a way to access the database column name. It's a complex API so I might have missed it.
Jamie Ide