views:

35

answers:

2

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.

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