NHibernate:查找属性是否映射到字段 [英] NHibernate: Finding out if a property is mapped to a field

查看:105
本文介绍了NHibernate:查找属性是否映射到字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以查找属性是否映射到字段. 我希望这样生成类似通用搜索"的内容:

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

如果我添加未映射到NHibernate的属性,则搜索将抛出NHibernate.QueryException,其描述为无法解析属性:C的Text1"

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

推荐答案

使用NHibernate元数据API.

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

这篇关于NHibernate:查找属性是否映射到字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆