NHibernate: figuring out whether a property maps to a field

Is there a way to find out if a property maps to a field. I would like this to create something like "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 that is not displayed in NHibernate, the search throws an NHibernate.QueryException with a description of "failed to resolve property: Text1 of: C"

I map the properties as follows:

class C
{    
    [Property(0, Column = "comment")]
    public virtual string Comment {get; set;}
}
+3
source share
1 answer

Use the NHibernate Metadata 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 + "%"));
        }
    }
}
+4
source

Source: https://habr.com/ru/post/1708247/


All Articles