NHibernate-ICriteria

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。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值