I was wondering if anyone knew how to find what column an entity's property is mapped to using NHibernate and only having the IEntityPersister interface available.
views:
35answers:
2
                
                A: 
                
                
              You could parse the mapping file if you are using one. It's fairly simple xml so a simple xpath query would get you the column name. If you are using attributes you would have to use reflection to get the attribute from the property.
                  olle
                   2009-08-19 23:34:58
                
              I have thought about doing that.  I was just hoping that there was an over looked/miss named property in the `IEntityPersister`  interface that let me find the column name without having to do the parsing.
                  MisterHux
                   2009-08-20 14:58:47
                
                
                A: 
                
                
              
            Here is some code that might help.
    public static string[] GetDatabaseColumnNamesFromEntityProperty(Type entityType, string propertyName)
    {
        PersistentClass aNHibernateClass = NHibernateSessionManager.Instance.GetNHibernateConfiguration().GetClassMapping(entityType);
        if (aNHibernateClass == null)
        {
            return null;
        }
        else
        {
            string[] columnNames = null;
            try
            {
                Property aProperty = aNHibernateClass.GetProperty(propertyName);
                columnNames = new string[aProperty.ColumnCollection.Count];
                int count = 0;
                foreach (Column column in aProperty.ColumnCollection)
                {
                    columnNames[count] = column.Name;
                    count++;
                }
            }
            catch(Exception)
            {
                Property aProperty = aNHibernateClass.IdentifierProperty;
                //if(aProperty.Name.Equals(propertyName))
                //{
                    columnNames = new string[aProperty.ColumnCollection.Count];
                    int count = 0;
                    foreach (Column column in aProperty.ColumnCollection)
                    {
                        columnNames[count] = column.Name;
                        count++;
                    }
                //}
            }
            return columnNames;
        }
    }
                  Craig
                   2010-06-25 06:26:41