bernhardrusch
bernhardrusch

Reputation: 11880

NHibernate: Finding out if a property is mapped to a field

Is there any way to find out if a property is mapped to a field. I would like this to generate something like a "generic like search":

    string[] words.
    words = search.Split(' ');
    Type type = typeof(T);

    Disjunction disjunction = new Disjunction();
    foreach (System.Reflection.PropertyInfo property in type.GetProperties())
    {
        if ((property.PropertyType == typeof(string)))
        {

            foreach (string word in words)
            {
                disjunction.Add(
                    Expression.InsensitiveLike(
                        property.Name,
                        "%" + word + "%"));
            }
        }
    }

If I add a property which is not mapped to NHibernate the search throws an NHibernate.QueryException with the description of "could not resolve property: Text1 of: C"

I am mapping the properties like this:

class C
{    
    [Property(0, Column = "comment")]
    public virtual string Comment {get; set;}
}

Upvotes: 3

Views: 2668

Answers (1)

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

Use the NHibernate meta data API.

ISessionFactory sessionFactory;

Type type = typeof(T);
IClassMetadata meta = sessionFactory.GetClassMetadata(type);

Disjunction disjunction = new Disjunction();
foreach (string mappedPropertyName in meta.PropertyNames)
{
    IType propertyType = meta.GetPropertyType(mappedPropertyName);

    if (propertyType == NHibernateUtil.String)
    {
        foreach (string word in words)
        {
            disjunction.Add(
                Expression.InsensitiveLike(
                    mappedPropertyName,
                    "%" + word + "%"));
        }
    }
}

Upvotes: 4

Related Questions