NHibernate:找出属性是否映射到字段

时间:2009-05-13 08:24:19

标签: nhibernate properties nhibernate-mapping nhibernate-metadata

有没有办法找出属性是否映射到字段。 我希望这能产生类似“类似搜索的通用”的东西:

    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 + "%"));
            }
        }
    }

如果我添加一个未映射到NHibernate的属性,搜索会抛出一个NHibernate.QueryException,其描述为“无法解析属性:Text1 of:C”

我正在映射这样的属性:

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

1 个答案:

答案 0 :(得分:4)

使用NHibernate元数据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 + "%"));
        }
    }
}