views:

658

answers:

3

I've got a class with a bunch of [ColumnName("foo")] NHibernate attributes. Is there an easy way to ask NHibernate to list all of the ColumnNames for a given class?

It sounds like it should be really easy but I'm just not seeing any kind of inspection in the NHibernate docs (or maybe I'm just blind today).

+1  A: 

Use LINQ and reflection:

var columns = typeof(TheClass).GetProperties()
    .Where(property => property.GetCustomAttributes(typeof(ColumnNameAttribute), false).Count > 0)
    .Select(property => property.Name);
Mehrdad Afshari
A: 

Use NHibernate's Metadata

// get an instance to the metadata 
IClassMetadata metadata = sessionfactory.GetClassMetadata(typeof(MyEntity));

// use properties and methods from the metadata:
// metadata.PropertyNames
// metadata.PropertyTypes
// metadata.GetIdentifier()
// and more

// or get the metadata for all classes at once
IDictionary allClassMetaData = factory.GetAllClassMetadata();
metadata = allClassMetaData[typeof(MyEntity)];

You get what NHibernate actually knows, independent of how it is defined; using attributes, xml mappings or FluentNHibernate. This makes it more stable and more reliable than using reflection on your own.

Stefan Steinegger
+2  A: 

I had this same problem, but found IClassMetadata doesn't have any column information, just property types, names, identifier, and table information.

What worked for me:

PersistentClass persistentClass = cfg.GetClassMapping(typeof(MyEntity));
Property property = persistentClass.GetProperty(propertyName);
property.ColumnIterator   // <-- the column(s) for the property
scamp