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查询时自定义一些条件然后进行详细查询。至于还有一些查询新名词,在真正使用的时候再去看也不迟,重要的是方法。