【问题标题】:NHibernate: Finding out if a property is mapped to a fieldNHibernate:找出一个属性是否映射到一个字段
【发布时间】:2009-05-13 08:24:19
【问题描述】:

有什么方法可以查明一个属性是否映射到一个字段。 我希望这能生成类似“通用搜索”之类的东西:

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

【问题讨论】:

    标签: nhibernate properties nhibernate-mapping nhibernate-metadata


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      相关资源
      最近更新 更多