NHibernate回顾之---条件查询(Criteria Query)

HQL极为强大,但是有些人希望能够动态的使用一种面向对象API创建查询,而不是在.NET代码中嵌入字符串。在NHibernate中,提供了一种直观的、可扩展的Criteria API。在我们键入查询语句的时候,提供了编译时的语法检查,VS提供了强大的智能提示。如果你对HQL的语法感觉不是很舒服的话,用这种方法可能更容易。这种API也比HQL更可扩展。

首先要使用条件查询,必须添加引用:using NHibernate.Criterion;

以下内容中NHelper.GetCurrentSession(),都是取得辅助内Nhelper中的Isession

 public static IList<Test> cwhere()
        {
            IList<Test> tes = NHelper.GetCurrentSession().CreateCriteria(typeof(Test)).Add(Restrictions.Like("Name", "xxx")).Add(Restrictions.Between("Id", 1, 5)).List<Test>();
            return tes;
 
        }

这个条件查询查询的是Test表中Name为xxx,ID在1到5之间的内容


        public static IList<Test> ccheck()
        {
           
           Test test=new Test(){
               Name="xxx",
               Password="***"
           };
            return NHelper.GetCurrentSession().CreateCriteria(typeof(Test)).Add(Example.Create(test)).List<Test>();


        }

这个为Example查询,查询Test表中Name为xxx,Password为***类似的内容
        public static IList<Test> cin(Test t)
        {
            Example example = Example.Create(t).IgnoreCase().EnableLike();
            return NHelper.GetCurrentSession().CreateCriteria(typeof(Test)).Add(example).List<Test>();
        }
这个为Example查询的另外一种方法。其实总结一下,条件查询就是where查询时自定义一些条件然后进行详细查询。至于还有一些查询新名词,在真正使用的时候再去看也不迟,重要的是方法。

   


转载于:https://www.cnblogs.com/bktmkd/archive/2012/05/22/2666003.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值