`
kamiff
  • 浏览: 88177 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

NHibernate-ICriteria

    博客分类:
  • C#
阅读更多
2、ICriteria,在例如产品分类这种树结构的表中,通常一个分类有它的子分类(集合),和他的父分类,一般我们查一级分类的条件是,那些父分类是空的分类:
        public IList<Category> GetRootCategories() 
        { 
            ICriteria crit = Session.CreateCriteria(this.PersistentClass); 
            crit.Add(Expression.Eq("Parent",null)); 
            return crit.List<Category>(); 
        } 

其中"Parent"是那个分类的父类这个Parent是对于类的属性而不是数据库字段,但是这样却查不到结果Nhibernate 产生如下的sql:"
exec sp_executesql N'SELECT this_.[s_id] as s1_1_0_, this_.[s_show] as s2_1_0_, this_.[s_order] as s3_1_0_, this_.[s_type] as s4_1_0_ FROM product_sort this_ WHERE this_.[s_type] = @p0 and this_.[s_show] = @p1', [email=N'@p0]N[/email] bigint,@p1 bit', @p0 = NULL, @p1 = 1" 

其中s_type就是对应了Parent但是这样是错误的正确的应该是产生如下的SQL:
exec sp_executesql N'SELECT this_.[s_id] as s1_1_0_, this_.[s_show] as s2_1_0_, this_.[s_order] as s3_1_0_, this_.[s_type] as s4_1_0_ FROM product_sort this_ WHERE this_.[s_type] is null and this_.[s_show] = @p1', [email=N'@p1]N[/email] bit',  @p1 = 1 

但是我们不可能因为这个而去修改它的源代码(哈哈其实这是典型99%对hibernate的使用不当范围内),只要改成
public IList<Category> GetRootCategories() 
        { 
            ICriteria crit = Session.CreateCriteria(this.PersistentClass); 
            crit.Add(new NullExpression("Parent")); 
            return crit.List<Category>(); 
        } 

就可以了,new NullExpression("Parent")会自动产生(is null)的sql。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics